Compare commits
40
Commits
4b73d2bea2
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb38b6bb04 | ||
|
|
cbcb739097 | ||
|
|
3f7c055489 | ||
|
|
d61a97de1e | ||
|
|
41649b0a05 | ||
|
|
651c9cddf8 | ||
|
|
10921deb34 | ||
|
|
e2f019667a | ||
|
|
336869e75f | ||
|
|
97eb41a0ea | ||
|
|
a3cd57e5d8 | ||
|
|
e4a81e8974 | ||
|
|
24a30881f3 | ||
|
|
2293ddb84d | ||
|
|
702694d4f4 | ||
|
|
d1f3dd5148 | ||
|
|
98c5f9eba0 | ||
|
|
dd92128464 | ||
|
|
f56caced32 | ||
|
|
d9eac0d1d2 | ||
|
|
67c5a906d1 | ||
|
|
20a3ce8896 | ||
|
|
e9da06fab5 | ||
|
|
d277e901f0 | ||
|
|
4f61c1fbd2 | ||
|
|
c0f8b98202 | ||
|
|
d7898d5678 | ||
|
|
6c0a2dbd2e | ||
|
|
f0462bd2a1 | ||
|
|
d4b1419f9a | ||
|
|
c79d96c5ec | ||
|
|
770a1833c8 | ||
|
|
7d8deaf79c | ||
|
|
9a84bbaa38 | ||
|
|
e091b5c8de | ||
|
|
aa326cf8b6 | ||
|
|
0f6cadc9c8 | ||
|
|
431d023c1a | ||
|
|
54ad7f7419 | ||
|
|
3270b48850 |
No files matched your search
@@ -42,6 +42,13 @@ The API can also run via `docker/docker-compose.yml` (reads `JWT_SECRET` from th
|
|||||||
|
|
||||||
### Project layout
|
### Project layout
|
||||||
|
|
||||||
|
The PHP backend has lived in the independent
|
||||||
|
[LehrerBackend repository](https://git.science-teaching.de/admin/LehrerBackend) since
|
||||||
|
2026-10-19 (local sibling `../LehrerBackend/`). `ai-backend/README.md` is only a pointer;
|
||||||
|
change PHP endpoints, providers, authentication and billing in LehrerBackend. Older
|
||||||
|
`ai-backend/...` paths in comments/TODO refer to the new repository root. Desktop clients and
|
||||||
|
DTOs stay here; no submodule or local backend checkout is needed to build the app.
|
||||||
|
|
||||||
- **LehrerApp.Core** — domain models (`Models/`), repository interfaces (`Interfaces/IRepositories.cs`),
|
- **LehrerApp.Core** — domain models (`Models/`), repository interfaces (`Interfaces/IRepositories.cs`),
|
||||||
and framework-free business services (`Services/`): `GradingService` (rounding, grading-key
|
and framework-free business services (`Services/`): `GradingService` (rounding, grading-key
|
||||||
validation, report-grade calculation), `SchoolYearService`, `AppLogger`, `BackupService`,
|
validation, report-grade calculation), `SchoolYearService`, `AppLogger`, `BackupService`,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.0.4" />
|
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.0.4" />
|
||||||
<PackageVersion Include="Avalonia.Fonts.Inter" Version="12.0.4" />
|
<PackageVersion Include="Avalonia.Fonts.Inter" Version="12.0.4" />
|
||||||
<PackageVersion Include="Avalonia.Controls.DataGrid" Version="12.0.0" />
|
<PackageVersion Include="Avalonia.Controls.DataGrid" Version="12.0.0" />
|
||||||
|
<PackageVersion Include="Avalonia.Labs.Lottie" Version="12.0.2" />
|
||||||
|
|
||||||
<!-- MVVM & DI – .NET 10 kompatibel -->
|
<!-- MVVM & DI – .NET 10 kompatibel -->
|
||||||
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.0" />
|
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.0" />
|
||||||
|
|||||||
@@ -29,6 +29,14 @@ public interface ISeatingPlanRepository
|
|||||||
/// wieder her (14.3). Tut nichts, falls der Papierkorb-Eintrag nicht (mehr) existiert.</summary>
|
/// wieder her (14.3). Tut nichts, falls der Papierkorb-Eintrag nicht (mehr) existiert.</summary>
|
||||||
void Restore(Guid trashId);
|
void Restore(Guid trashId);
|
||||||
}
|
}
|
||||||
|
public interface IStudentGroupPlanRepository
|
||||||
|
{
|
||||||
|
StudentGroupPlan? GetById(Guid id);
|
||||||
|
List<StudentGroupPlan> GetByGroup(Guid groupId);
|
||||||
|
List<StudentGroupPlan> GetByStudent(Guid studentId);
|
||||||
|
void Save(StudentGroupPlan plan);
|
||||||
|
void Delete(Guid id);
|
||||||
|
}
|
||||||
public interface IGroupMembershipRepository
|
public interface IGroupMembershipRepository
|
||||||
{
|
{
|
||||||
List<GroupMembership> GetByStudent(Guid studentId);
|
List<GroupMembership> GetByStudent(Guid studentId);
|
||||||
@@ -86,6 +94,13 @@ public interface IReportGradeRepository
|
|||||||
void Save(ReportGrade grade);
|
void Save(ReportGrade grade);
|
||||||
void Delete(Guid id);
|
void Delete(Guid id);
|
||||||
}
|
}
|
||||||
|
public interface IInterimGradeRepository
|
||||||
|
{
|
||||||
|
List<InterimGrade> GetByGroup(Guid groupId);
|
||||||
|
List<InterimGrade> GetByStudentAndGroup(Guid studentId, Guid groupId);
|
||||||
|
void Save(InterimGrade grade);
|
||||||
|
void Delete(Guid id);
|
||||||
|
}
|
||||||
public interface IUnitRepository
|
public interface IUnitRepository
|
||||||
{
|
{
|
||||||
Unit? GetById(Guid id);
|
Unit? GetById(Guid id);
|
||||||
@@ -218,6 +233,14 @@ public interface IVorgangRepository
|
|||||||
/// Markiert den Vorgang als gelöscht, statt ihn hart zu entfernen (gleiches Muster wie Documentation).
|
/// Markiert den Vorgang als gelöscht, statt ihn hart zu entfernen (gleiches Muster wie Documentation).
|
||||||
void Delete(Guid id);
|
void Delete(Guid id);
|
||||||
}
|
}
|
||||||
|
/// "Zurückstellen"-Zeitstempel für Dashboard-Warnungen je (StudentId, WarningTag) — wird
|
||||||
|
/// synchronisiert, siehe DashboardWarningSnooze.
|
||||||
|
public interface IDashboardWarningSnoozeRepository
|
||||||
|
{
|
||||||
|
DashboardWarningSnooze? Get(Guid studentId, string warningTag);
|
||||||
|
List<DashboardWarningSnooze> GetAll();
|
||||||
|
void Save(DashboardWarningSnooze snooze);
|
||||||
|
}
|
||||||
public interface IWorkTaskRepository
|
public interface IWorkTaskRepository
|
||||||
{
|
{
|
||||||
List<WorkTask> GetByStatus(WorkTaskStatus status);
|
List<WorkTask> GetByStatus(WorkTaskStatus status);
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LehrerApp.Core.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "Zurückstellen" einer klassenübergreifenden Dashboard-Warnung (Fehlzeiten/Hausaufgaben/
|
||||||
|
/// Verspätungen, siehe DashboardViewModel) für eine Person — ein Erinnerungs-Zeitstempel je
|
||||||
|
/// (StudentId, WarningTag), der über den Sync repliziert wird, damit eine auf Gerät A
|
||||||
|
/// zurückgestellte Warnung auf Gerät B nicht weiter rot oben steht.
|
||||||
|
/// </summary>
|
||||||
|
public class DashboardWarningSnooze
|
||||||
|
{
|
||||||
|
/// Aus (StudentId, WarningTag) abgeleitet (siehe <see cref="IdFor"/>; setzt
|
||||||
|
/// IDashboardWarningSnoozeRepository.Save) statt zufällig: stellen
|
||||||
|
/// zwei Geräte dieselbe Warnung unabhängig voneinander zurück, beschreiben sie so denselben
|
||||||
|
/// Datensatz (Last-Write-Wins im Sync), statt zwei Datensätze anzulegen, die beim Anwenden am
|
||||||
|
/// Unique-Index ux_student_tag scheitern würden.
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public Guid StudentId { get; set; }
|
||||||
|
/// Dieselben Strings wie VorgangTagDisplay.Suggestions ("Absentismus"/"Hausaufgaben"/"Verspätungen").
|
||||||
|
public string WarningTag { get; set; } = "";
|
||||||
|
public DateOnly SnoozedUntil { get; set; }
|
||||||
|
|
||||||
|
public static Guid IdFor(Guid studentId, string warningTag)
|
||||||
|
{
|
||||||
|
var hash = SHA256.HashData(Encoding.UTF8.GetBytes($"{studentId:N}:{warningTag.ToLowerInvariant()}"));
|
||||||
|
return new Guid(hash.AsSpan(0, 16));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,6 +22,20 @@ public class Exam
|
|||||||
/// auf der Klausuren-Hauptseite — Id der "Ursprungs"-Klausur, gesetzt beim Duplizieren
|
/// auf der Klausuren-Hauptseite — Id der "Ursprungs"-Klausur, gesetzt beim Duplizieren
|
||||||
/// (siehe ExamDialogViewModel.Save).
|
/// (siehe ExamDialogViewModel.Save).
|
||||||
public Guid? SharedExamGroupId { get; set; }
|
public Guid? SharedExamGroupId { get; set; }
|
||||||
|
/// <summary>Optional verknüpfte ursprüngliche Arbeit derselben Lerngruppe.</summary>
|
||||||
|
public Guid? RepeatOfExamId { get; set; }
|
||||||
|
public RepeatGradeRule RepeatGradeRule { get; set; } = RepeatGradeRule.Better;
|
||||||
|
/// <summary>Art der Leistungsüberprüfung. Nur <see cref="ExamKind.Klausur"/> zählt in die
|
||||||
|
/// schriftliche Note; alle anderen Arten fließen unter "Sonstige" ein.</summary>
|
||||||
|
public ExamKind Kind { get; set; } = ExamKind.Klausur;
|
||||||
|
/// <summary>Nachschreibarbeit: inhaltlich eigene Arbeit für Schüler, die die verknüpfte
|
||||||
|
/// erste Arbeit (<see cref="RepeatOfExamId"/>) versäumt haben. Anders als eine Wiederholung
|
||||||
|
/// wird sie nur von diesen Schülern geschrieben und ersetzt deren fehlende Note.</summary>
|
||||||
|
public bool IsMakeUp { get; set; }
|
||||||
|
/// <summary>Förderarbeit: inhaltlich eigene Arbeit, die einzelne Schüler statt der verknüpften
|
||||||
|
/// ersten Arbeit schreiben — typischerweise am selben Tag, daher darf sie am Datum der ersten
|
||||||
|
/// Arbeit liegen. Zählt wie eine Nachschreibarbeit (ersetzt nur eine fehlende Note).</summary>
|
||||||
|
public bool IsSupportWork { get; set; }
|
||||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
@@ -31,6 +45,9 @@ public class ExamTask
|
|||||||
public string? Title { get; set; }
|
public string? Title { get; set; }
|
||||||
public double MaxPoints { get; set; }
|
public double MaxPoints { get; set; }
|
||||||
public double Weight { get; set; } = 1.0;
|
public double Weight { get; set; } = 1.0;
|
||||||
|
/// <summary>Null gilt für beide Fassungen; A/B nur für die gewählte Fassung.</summary>
|
||||||
|
public ExamVariant? Variant { get; set; }
|
||||||
|
public bool IsBonus { get; set; }
|
||||||
public List<CompetencyReference> Competencies { get; set; } = [];
|
public List<CompetencyReference> Competencies { get; set; } = [];
|
||||||
}
|
}
|
||||||
public class GradingKeyEntry
|
public class GradingKeyEntry
|
||||||
@@ -55,7 +72,32 @@ public class ExamResult
|
|||||||
public double TotalPoints { get; set; }
|
public double TotalPoints { get; set; }
|
||||||
public string? Grade { get; set; }
|
public string? Grade { get; set; }
|
||||||
public bool Absent { get; set; }
|
public bool Absent { get; set; }
|
||||||
|
public ExamVariant Variant { get; set; } = ExamVariant.A;
|
||||||
public string? Comment { get; set; }
|
public string? Comment { get; set; }
|
||||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
public enum ExamStatus { Planned, Conducted, Graded, Returned }
|
public enum ExamStatus { Planned, Conducted, Graded, Returned }
|
||||||
|
public enum ExamVariant { A, B }
|
||||||
|
public enum RepeatGradeRule { Better, Repeat, Original }
|
||||||
|
/// <summary>Reihenfolge ist persistiert (LiteDB speichert den Enum-Wert) — nur hinten anhängen.</summary>
|
||||||
|
public enum ExamKind { Klausur, Test, KontrollierteHausaufgabe, Sonstiges }
|
||||||
|
|
||||||
|
public static class ExamFollowUpExtensions
|
||||||
|
{
|
||||||
|
/// <summary>Nachschreib- und Förderarbeiten sind inhaltlich eigene Arbeiten nur für einzelne
|
||||||
|
/// Schüler: ihre Note ersetzt eine fehlende Note der ersten Arbeit, verdrängt sie aber nie.</summary>
|
||||||
|
public static bool ReplacesMissingGrade(this Exam exam) => exam.IsMakeUp || exam.IsSupportWork;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class ExamKindExtensions
|
||||||
|
{
|
||||||
|
public static bool CountsAsWritten(this ExamKind kind) => kind == ExamKind.Klausur;
|
||||||
|
|
||||||
|
public static string Label(this ExamKind kind) => kind switch
|
||||||
|
{
|
||||||
|
ExamKind.Test => "Test",
|
||||||
|
ExamKind.KontrollierteHausaufgabe => "Kontrollierte Hausaufgabe",
|
||||||
|
ExamKind.Sonstiges => "Sonstige Arbeit",
|
||||||
|
_ => "Klausur",
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -31,7 +31,8 @@ public class LearningGroup
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// WebUntis-interne Unterrichtsnummer (lsid) dieser Lerngruppe, Grundlage für den Abruf des
|
/// WebUntis-interne Unterrichtsnummer (lsid) dieser Lerngruppe, Grundlage für den Abruf des
|
||||||
/// "Fehlzeiten pro Unterricht"-Berichts. Wird von WebUntis pro Schuljahr neu vergeben und muss
|
/// "Fehlzeiten pro Unterricht"-Berichts. Wird von WebUntis pro Schuljahr neu vergeben und muss
|
||||||
/// deshalb händisch je Lerngruppe/Schuljahr gepflegt werden - keine JSON-RPC-Methode liefert sie.
|
/// deshalb je Lerngruppe/Schuljahr gepflegt werden. Der manuelle WebUntis-Zuordnungsabgleich
|
||||||
|
/// kann sie aus dem Wochenstundenplan übernehmen.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int? WebUntisLessonId { get; set; }
|
public int? WebUntisLessonId { get; set; }
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -67,6 +68,11 @@ public class GroupMembership
|
|||||||
public DateOnly? JoinedAt { get; set; }
|
public DateOnly? JoinedAt { get; set; }
|
||||||
public DateOnly? LeftAt { get; set; }
|
public DateOnly? LeftAt { get; set; }
|
||||||
public Niveau? Niveau { get; set; }
|
public Niveau? Niveau { get; set; }
|
||||||
|
/// <summary>Förderschüler-Markierung, unabhängig von der Niveaudifferenzierung der Gruppe
|
||||||
|
/// (<see cref="LearningGroup.IsDifferentiated"/>): auch in einem nicht differenzierten Kurs
|
||||||
|
/// bekommen einzelne Schüler eigenes Fördermaterial. Auswertung siehe
|
||||||
|
/// <see cref="Services.GroupMembershipService.IsSupportStudent"/>.</summary>
|
||||||
|
public bool IsSupportStudent { get; set; }
|
||||||
}
|
}
|
||||||
public enum MembershipPeriod { FullYear, H1Only, H2Only, Custom }
|
public enum MembershipPeriod { FullYear, H1Only, H2Only, Custom }
|
||||||
public enum GroupType { Class, Course }
|
public enum GroupType { Class, Course }
|
||||||
|
|||||||
@@ -258,6 +258,42 @@ public class ReportGrade
|
|||||||
public string? OverrideValue { get; set; }
|
public string? OverrideValue { get; set; }
|
||||||
public string? OverrideReason { get; set; }
|
public string? OverrideReason { get; set; }
|
||||||
public bool IsLocked { get; set; }
|
public bool IsLocked { get; set; }
|
||||||
|
/// <summary>Nur am Datensatz "Gesamtes Schuljahr": Note der Projektprüfung, wenn sie in
|
||||||
|
/// diesem Fach abgelegt wurde (Klasse 10). Zählt in der Endjahresnote wie ein weiteres
|
||||||
|
/// Halbjahr.</summary>
|
||||||
|
public string? ProjectExamGrade { get; set; }
|
||||||
|
/// <summary>Wie <see cref="ProjectExamGrade"/>, für die mündliche Abschlussprüfung im
|
||||||
|
/// gewählten Fach.</summary>
|
||||||
|
public string? OralExamGrade { get; set; }
|
||||||
|
/// <summary>Note der schriftlichen Abschlussprüfung (Deutsch, Mathematik, erste
|
||||||
|
/// Fremdsprache), nur am Jahres-Datensatz.</summary>
|
||||||
|
public string? WrittenExamGrade { get; set; }
|
||||||
|
/// <summary>Note einer zusätzlichen mündlichen Prüfung ("Nachprüfung", § 8 Abs. 3 und 4
|
||||||
|
/// PrüfV Sek. I), nur am Jahres-Datensatz. Zur Verrechnung siehe docs/Datenmodell.md.</summary>
|
||||||
|
public string? AdditionalOralExamGrade { get; set; }
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Zwischenstand: eine vorläufige Note zu einem Stichtag, wie sie zu einem Anlass (Sprechtag,
|
||||||
|
/// blauer Brief, Konferenz, Elternanfrage) genannt wurde. Bewusst getrennt von
|
||||||
|
/// <see cref="ReportGrade"/> — mehrere je Halbjahr möglich, ohne Einfluss auf die Zeugnisnote.
|
||||||
|
/// Zwischenstände mit gleichem <see cref="Date"/> und <see cref="Occasion"/> bilden einen
|
||||||
|
/// Durchgang durch (einen Teil der) Lerngruppe.
|
||||||
|
/// </summary>
|
||||||
|
public class InterimGrade
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
public Guid StudentId { get; set; }
|
||||||
|
public Guid GroupId { get; set; }
|
||||||
|
/// <summary>Stichtag: Leistungen bis einschließlich dieses Tages lagen der Note zugrunde.</summary>
|
||||||
|
public DateOnly Date { get; set; }
|
||||||
|
public string Occasion { get; set; } = "";
|
||||||
|
public string? WrittenValue { get; set; }
|
||||||
|
public string? OralValue { get; set; }
|
||||||
|
public string OverallValue { get; set; } = "";
|
||||||
|
public string? Note { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -52,9 +52,10 @@ public sealed record StudentReferenceSummary(
|
|||||||
int Grades,
|
int Grades,
|
||||||
int ReportGrades,
|
int ReportGrades,
|
||||||
int ParticipationEntries,
|
int ParticipationEntries,
|
||||||
int DocumentationEntries)
|
int DocumentationEntries,
|
||||||
|
int StudentGroupPlans = 0)
|
||||||
{
|
{
|
||||||
public int Total => Memberships + ExamResults + Grades + ReportGrades
|
public int Total => Memberships + ExamResults + Grades + ReportGrades
|
||||||
+ ParticipationEntries + DocumentationEntries;
|
+ ParticipationEntries + DocumentationEntries + StudentGroupPlans;
|
||||||
public bool HasReferences => Total > 0;
|
public bool HasReferences => Total > 0;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace LehrerApp.Core.Models;
|
||||||
|
|
||||||
|
/// <summary>Eine wiederverwendbare Einteilung innerhalb einer Lerngruppe.</summary>
|
||||||
|
public class StudentGroupPlan
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
public Guid GroupId { get; set; }
|
||||||
|
public string Name { get; set; } = "";
|
||||||
|
public List<StudentGroupPlanGroup> Groups { get; set; } = [];
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class StudentGroupPlanGroup
|
||||||
|
{
|
||||||
|
public List<Guid> StudentIds { get; set; } = [];
|
||||||
|
}
|
||||||
@@ -71,6 +71,7 @@ public enum UntisCacheKind { Absences, ClassRegister, Roster }
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class UntisCacheFetchState
|
public class UntisCacheFetchState
|
||||||
{
|
{
|
||||||
|
public int AbsenceReportVersion { get; set; }
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
public string ClassName { get; set; } = "";
|
public string ClassName { get; set; } = "";
|
||||||
public UntisCacheKind Kind { get; set; }
|
public UntisCacheKind Kind { get; set; }
|
||||||
|
|||||||
@@ -3,7 +3,14 @@ namespace LehrerApp.Core.Models;
|
|||||||
public class Documentation : IHasAttachments
|
public class Documentation : IHasAttachments
|
||||||
{
|
{
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
/// <summary>Hauptperson des Eintrags (bei Gruppeneinträgen <see cref="Guid.Empty"/>).</summary>
|
||||||
public Guid StudentId { get; set; }
|
public Guid StudentId { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Weitere betroffene Schüler*innen, z.B. bei einem Vorgang mit mehreren Beteiligten: der Eintrag
|
||||||
|
/// existiert nur einmal, erscheint aber bei jeder dieser Personen (siehe <see cref="Concerns"/>).
|
||||||
|
/// Enthält nie <see cref="StudentId"/> selbst.
|
||||||
|
/// </summary>
|
||||||
|
public List<Guid> AdditionalStudentIds { get; set; } = [];
|
||||||
public Guid? GroupId { get; set; }
|
public Guid? GroupId { get; set; }
|
||||||
/// <summary>Unterrichtssitzung, in der die Beobachtung entstanden ist.</summary>
|
/// <summary>Unterrichtssitzung, in der die Beobachtung entstanden ist.</summary>
|
||||||
public Guid? ParticipationSessionId { get; set; }
|
public Guid? ParticipationSessionId { get; set; }
|
||||||
@@ -33,6 +40,14 @@ public class Documentation : IHasAttachments
|
|||||||
// Löschen entfernt den Eintrag nicht hart, sondern markiert ihn nur (Nachvollziehbarkeit, 5.1.4).
|
// Löschen entfernt den Eintrag nicht hart, sondern markiert ihn nur (Nachvollziehbarkeit, 5.1.4).
|
||||||
public bool IsDeleted { get; set; }
|
public bool IsDeleted { get; set; }
|
||||||
public DateTime? DeletedAt { get; set; }
|
public DateTime? DeletedAt { get; set; }
|
||||||
|
|
||||||
|
/// Ob der Eintrag diese Person betrifft — als Hauptperson oder als weitere Beteiligte.
|
||||||
|
public bool Concerns(Guid studentId) =>
|
||||||
|
studentId != Guid.Empty && (StudentId == studentId || AdditionalStudentIds.Contains(studentId));
|
||||||
|
|
||||||
|
/// Hauptperson (falls gesetzt) gefolgt von den weiteren Beteiligten.
|
||||||
|
public IEnumerable<Guid> InvolvedStudentIds() =>
|
||||||
|
(StudentId == Guid.Empty ? [] : new[] { StudentId }).Concat(AdditionalStudentIds);
|
||||||
}
|
}
|
||||||
public class AbsenceData
|
public class AbsenceData
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
|
||||||
|
namespace LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
/// <summary>Eine Spalte der Punktetabelle auf dem Klausur-Deckblatt. Bonusaufgaben tragen keine
|
||||||
|
/// Nummer; <see cref="AchievedPoints"/> ist null, solange nichts eingetragen werden soll.</summary>
|
||||||
|
public sealed record ExamCoverTaskColumn(string Number, double MaxPoints, bool IsBonus, double? AchievedPoints);
|
||||||
|
|
||||||
|
public static class ExamCoverSheetService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Spalten für genau die Fassung, die der Schüler geschrieben hat. Nummeriert wird innerhalb
|
||||||
|
/// dieser Fassung (wie auf dem gedruckten Aufgabenblatt), Bonusaufgaben zählen nicht mit.
|
||||||
|
/// <paramref name="points"/> folgt wie <see cref="ExamResult.Points"/> der Reihenfolge aller
|
||||||
|
/// Aufgaben, nicht nur der dieser Fassung.
|
||||||
|
/// </summary>
|
||||||
|
public static List<ExamCoverTaskColumn> Columns(IReadOnlyList<ExamTask> orderedTasks, ExamVariant variant,
|
||||||
|
IReadOnlyList<double>? points)
|
||||||
|
{
|
||||||
|
var columns = new List<ExamCoverTaskColumn>();
|
||||||
|
var number = 0;
|
||||||
|
for (var index = 0; index < orderedTasks.Count; index++)
|
||||||
|
{
|
||||||
|
var task = orderedTasks[index];
|
||||||
|
if (!ExamScoringService.AppliesTo(task, variant)) continue;
|
||||||
|
double? achieved = points is null ? null : index < points.Count ? points[index] : 0;
|
||||||
|
columns.Add(new(task.IsBonus ? "" : (++number).ToString(), task.MaxPoints, task.IsBonus, achieved));
|
||||||
|
}
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Ein Ergebnis gilt als korrigiert, sobald Punkte oder eine Note eingetragen sind.</summary>
|
||||||
|
public static bool IsCorrected(ExamResult? result) =>
|
||||||
|
result is { Absent: false } && (result.Points.Count > 0 || !string.IsNullOrWhiteSpace(result.Grade));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Wer eine Arbeit mitschreibt — eine Regel für Punkteeingabe und Deckblätter.</summary>
|
||||||
|
public static class ExamParticipantService
|
||||||
|
{
|
||||||
|
/// <summary>Bei einer Nachschreib- oder Förderarbeit: Schüler, die die erste Arbeit bereits mit
|
||||||
|
/// Note geschrieben haben. Sonst leer.</summary>
|
||||||
|
public static HashSet<Guid> WroteOriginal(Exam exam, Func<Guid, List<ExamResult>> resultsByExam)
|
||||||
|
{
|
||||||
|
var wroteOriginal = new HashSet<Guid>();
|
||||||
|
if (exam.ReplacesMissingGrade() && exam.RepeatOfExamId is { } originalId)
|
||||||
|
foreach (var r in resultsByExam(originalId).Where(r => !r.Absent && r.Grade is not null))
|
||||||
|
wroteOriginal.Add(r.StudentId);
|
||||||
|
return wroteOriginal;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool Includes(Exam exam, GroupMembership? membership, bool hasResult, bool wroteOriginal)
|
||||||
|
{
|
||||||
|
if (membership is not null && !GroupMembershipService.IsActiveOn(membership, exam.Date)) return false;
|
||||||
|
// Niveau-Klausur: nur Schüler mit passendem Niveau. Klausuren ohne Niveau-Zuordnung gelten
|
||||||
|
// weiterhin für die ganze Gruppe.
|
||||||
|
if (exam.Niveau.HasValue && membership?.Niveau != exam.Niveau) return false;
|
||||||
|
// Förderarbeit: nur Förderschüler (außer es gibt hier bereits ein Ergebnis).
|
||||||
|
if (exam.IsSupportWork && !hasResult && !GroupMembershipService.IsSupportStudent(membership)) return false;
|
||||||
|
// Nachschreib-/Förderarbeit: wer die erste Arbeit schon mit Note geschrieben hat, taucht nicht auf —
|
||||||
|
// außer es gibt hier bereits ein Ergebnis (nichts verstecken, was schon eingetragen wurde).
|
||||||
|
return hasResult || !wroteOriginal;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
/// <summary>Reihenfolge, in der Enter bei der Punkteeingabe zum nächsten Feld springt.</summary>
|
||||||
|
public enum GradingEntryOrder
|
||||||
|
{
|
||||||
|
/// Eine Arbeit komplett, dann die nächste (Enter läuft die Zeile entlang).
|
||||||
|
ByStudent,
|
||||||
|
/// Eine Aufgabe für alle, dann die nächste (Enter läuft die Spalte hinunter).
|
||||||
|
ByTask,
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ExamGradingSettings
|
||||||
|
{
|
||||||
|
public GradingEntryOrder EntryOrder { get; set; } = GradingEntryOrder.ByStudent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Merkt sich den zuletzt gewählten Korrekturmodus der Punkteeingabe lokal.</summary>
|
||||||
|
public sealed class ExamGradingSettingsService
|
||||||
|
{
|
||||||
|
private readonly string _configPath;
|
||||||
|
|
||||||
|
public ExamGradingSettingsService(string appDataPath) =>
|
||||||
|
_configPath = Path.Combine(appDataPath, "examgradingsettings.json");
|
||||||
|
|
||||||
|
public ExamGradingSettings Load()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (File.Exists(_configPath))
|
||||||
|
return JsonSerializer.Deserialize<ExamGradingSettings>(File.ReadAllText(_configPath))
|
||||||
|
?? new ExamGradingSettings();
|
||||||
|
}
|
||||||
|
catch { /* beschädigte Konfiguration -> Standard */ }
|
||||||
|
return new ExamGradingSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Save(ExamGradingSettings settings)
|
||||||
|
{
|
||||||
|
try { File.WriteAllText(_configPath, JsonSerializer.Serialize(settings)); }
|
||||||
|
catch { /* Einstellung ist Komfort — Fehler beim Schreiben nicht an die UI durchreichen */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
|
||||||
|
namespace LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
public static class ExamScoringService
|
||||||
|
{
|
||||||
|
public static bool AppliesTo(ExamTask task, ExamVariant variant) =>
|
||||||
|
task.Variant is null || task.Variant == variant;
|
||||||
|
|
||||||
|
public static double Maximum(IEnumerable<ExamTask> tasks, ExamVariant variant) =>
|
||||||
|
tasks.Where(t => AppliesTo(t, variant) && !t.IsBonus).Sum(t => t.MaxPoints);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Anzeigenummern der Aufgaben in der gespeicherten Reihenfolge. Bonusaufgaben werden auf
|
||||||
|
/// dem Aufgabenblatt üblicherweise nicht nummeriert — würden sie mitgezählt, passten alle
|
||||||
|
/// Nummern hinter einer Bonusaufgabe nicht mehr zur gedruckten Arbeit. Sie heißen daher
|
||||||
|
/// "Bonus" (bei mehreren "Bonus 1", "Bonus 2", …). <see cref="ExamTask.Nr"/> bleibt davon
|
||||||
|
/// unberührt die reine Positions-/Sortiernummer.
|
||||||
|
/// </summary>
|
||||||
|
public static List<string> TaskNumbers(IEnumerable<bool> isBonus)
|
||||||
|
{
|
||||||
|
var flags = isBonus.ToList();
|
||||||
|
var multipleBonus = flags.Count(b => b) > 1;
|
||||||
|
int nr = 0, bonus = 0;
|
||||||
|
return flags.Select(b => b
|
||||||
|
? multipleBonus ? $"Bonus {++bonus}" : "Bonus"
|
||||||
|
: (++nr).ToString())
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Beschriftung je Aufgabe ("Aufgabe 3", "3. Titel", "Bonus", "Bonus: Titel").</summary>
|
||||||
|
public static List<string> TaskLabels(IReadOnlyList<ExamTask> orderedTasks) =>
|
||||||
|
TaskNumbers(orderedTasks.Select(t => t.IsBonus))
|
||||||
|
.Select((number, i) =>
|
||||||
|
{
|
||||||
|
var title = orderedTasks[i].Title;
|
||||||
|
if (orderedTasks[i].IsBonus)
|
||||||
|
return string.IsNullOrWhiteSpace(title) ? number : $"{number}: {title}";
|
||||||
|
return string.IsNullOrWhiteSpace(title) ? $"Aufgabe {number}" : $"{number}. {title}";
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
public static double Achieved(IReadOnlyList<ExamTask> tasks, IReadOnlyList<double> points,
|
||||||
|
ExamVariant variant) => tasks.Select((task, index) =>
|
||||||
|
AppliesTo(task, variant) && index < points.Count ? points[index] : 0).Sum();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wählt pro Arbeit samt allen verknüpften Folgearbeiten (Wiederholung, Nachschreib-/Förderarbeit)
|
||||||
|
/// genau eine Note. Andere Arbeiten bleiben erhalten. Fehlt die erste Arbeit (Schüler war
|
||||||
|
/// abwesend), zählt die Nachschreib-/Förderarbeit allein; hat der Schüler beide geschrieben,
|
||||||
|
/// zählt immer die erste — sie ersetzen nur eine fehlende Note.
|
||||||
|
/// </summary>
|
||||||
|
public static List<string> EffectiveGrades(IEnumerable<(Exam Exam, string Grade)> entries,
|
||||||
|
GradingSystem system)
|
||||||
|
{
|
||||||
|
var chains = new List<List<(Exam Exam, string Grade)>>();
|
||||||
|
var chainByRoot = new Dictionary<Guid, List<(Exam Exam, string Grade)>>();
|
||||||
|
foreach (var entry in entries)
|
||||||
|
{
|
||||||
|
var root = entry.Exam.RepeatOfExamId ?? entry.Exam.Id;
|
||||||
|
if (!chainByRoot.TryGetValue(root, out var chain))
|
||||||
|
chains.Add(chainByRoot[root] = chain = []);
|
||||||
|
chain.Add(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = new List<string>();
|
||||||
|
foreach (var chain in chains)
|
||||||
|
{
|
||||||
|
// Die erste Arbeit steht vorn, Folgearbeiten chronologisch dahinter.
|
||||||
|
var ordered = chain.OrderBy(x => x.Exam.RepeatOfExamId is null ? 0 : 1)
|
||||||
|
.ThenBy(x => x.Exam.Date).ToList();
|
||||||
|
var current = ordered[0].Grade;
|
||||||
|
foreach (var next in ordered.Skip(1))
|
||||||
|
current = Choose(current, next.Grade,
|
||||||
|
next.Exam.ReplacesMissingGrade() ? RepeatGradeRule.Original : next.Exam.RepeatGradeRule, system);
|
||||||
|
result.Add(current);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wie <see cref="EffectiveGrades"/>, trennt aber nach Art: Klausuren zählen als schriftliche
|
||||||
|
/// Note, Tests u. Ä. fließen unter "Sonstige" ein. Verknüpfte Arbeiten erben die Art der
|
||||||
|
/// ersten Arbeit (der Dialog erzwingt das), landen also immer im selben Topf.
|
||||||
|
/// </summary>
|
||||||
|
public static (List<string> Written, List<string> Other) EffectiveGradesByKind(
|
||||||
|
IEnumerable<(Exam Exam, string Grade)> entries, GradingSystem system)
|
||||||
|
{
|
||||||
|
var list = entries.ToList();
|
||||||
|
return (
|
||||||
|
EffectiveGrades(list.Where(x => x.Exam.Kind.CountsAsWritten()), system),
|
||||||
|
EffectiveGrades(list.Where(x => !x.Exam.Kind.CountsAsWritten()), system));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Choose(string original, string repeat, RepeatGradeRule rule, GradingSystem system)
|
||||||
|
{
|
||||||
|
if (rule == RepeatGradeRule.Original) return original;
|
||||||
|
if (rule == RepeatGradeRule.Repeat) return repeat;
|
||||||
|
var first = GradeValue(original, system);
|
||||||
|
var second = GradeValue(repeat, system);
|
||||||
|
if (first is null || second is null) return original;
|
||||||
|
return system == GradingSystem.Grades1To6
|
||||||
|
? (second < first ? repeat : original)
|
||||||
|
: (second > first ? repeat : original);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double? GradeValue(string grade, GradingSystem system)
|
||||||
|
{
|
||||||
|
var core = grade.Trim();
|
||||||
|
var tendency = 0.0;
|
||||||
|
if (core.EndsWith('+')) { tendency = system == GradingSystem.Grades1To6 ? -1.0 / 3 : 1.0 / 3; core = core[..^1]; }
|
||||||
|
else if (core.EndsWith('-')) { tendency = system == GradingSystem.Grades1To6 ? 1.0 / 3 : -1.0 / 3; core = core[..^1]; }
|
||||||
|
return double.TryParse(core.Trim(), System.Globalization.NumberStyles.Any,
|
||||||
|
System.Globalization.CultureInfo.InvariantCulture, out var value) ? value + tendency : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,7 +10,8 @@ namespace LehrerApp.Core.Services;
|
|||||||
/// fehlt, ist die persönliche Belastung der Lehrkraft: mehr eigene Klausuren in derselben Woche
|
/// fehlt, ist die persönliche Belastung der Lehrkraft: mehr eigene Klausuren in derselben Woche
|
||||||
/// bedeuten unabhängig von der Klasse mehr Erstellungsaufwand vorher und mehr Korrekturaufwand
|
/// bedeuten unabhängig von der Klasse mehr Erstellungsaufwand vorher und mehr Korrekturaufwand
|
||||||
/// danach. Da eine LiteDB-Datei genau einem Nutzer gehört (siehe CLAUDE.md), sind "alle
|
/// danach. Da eine LiteDB-Datei genau einem Nutzer gehört (siehe CLAUDE.md), sind "alle
|
||||||
/// Klausuren in der Datenbank" bereits gleichbedeutend mit "meine Klausuren".
|
/// Klausuren in der Datenbank" bereits gleichbedeutend mit "meine Klausuren". Tests und andere
|
||||||
|
/// kurze Arbeiten (<see cref="ExamKind"/>) zählen bewusst nicht mit — sie sind kein Klausurblock.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class ExamWeekLoadService
|
public static class ExamWeekLoadService
|
||||||
{
|
{
|
||||||
@@ -24,7 +25,8 @@ public static class ExamWeekLoadService
|
|||||||
public static int CountInSameWeek(IEnumerable<Exam> allExams, DateOnly date, Guid? excludeExamId = null)
|
public static int CountInSameWeek(IEnumerable<Exam> allExams, DateOnly date, Guid? excludeExamId = null)
|
||||||
{
|
{
|
||||||
var (year, week) = IsoWeek(date);
|
var (year, week) = IsoWeek(date);
|
||||||
return allExams.Count(e => e.Id != excludeExamId && IsoWeek(e.Date) == (year, week));
|
return allExams.Count(e => e.Id != excludeExamId && e.Kind.CountsAsWritten()
|
||||||
|
&& IsoWeek(e.Date) == (year, week));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gruppiert die übergebenen Klausuren nach ISO-Kalenderwoche und liefert nur die Wochen mit
|
/// Gruppiert die übergebenen Klausuren nach ISO-Kalenderwoche und liefert nur die Wochen mit
|
||||||
@@ -32,6 +34,7 @@ public static class ExamWeekLoadService
|
|||||||
/// vorausschauenden Überblick (z.B. Dashboard), nicht für die Einzelprüfung beim Anlegen.
|
/// vorausschauenden Überblick (z.B. Dashboard), nicht für die Einzelprüfung beim Anlegen.
|
||||||
public static List<ExamWeekLoad> FindOverloadedWeeks(IEnumerable<Exam> exams) =>
|
public static List<ExamWeekLoad> FindOverloadedWeeks(IEnumerable<Exam> exams) =>
|
||||||
exams
|
exams
|
||||||
|
.Where(e => e.Kind.CountsAsWritten())
|
||||||
.GroupBy(e => IsoWeek(e.Date))
|
.GroupBy(e => IsoWeek(e.Date))
|
||||||
.Where(g => g.Count() >= WarningThreshold)
|
.Where(g => g.Count() >= WarningThreshold)
|
||||||
.Select(g => new ExamWeekLoad(g.Key.Year, g.Key.Week, WeekStart(g.Key.Year, g.Key.Week), g.Count()))
|
.Select(g => new ExamWeekLoad(g.Key.Year, g.Key.Week, WeekStart(g.Key.Year, g.Key.Week), g.Count()))
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ public class GradingService
|
|||||||
/// Wandelt eine Notenangabe mit optionaler Tendenz ("3+", "2-") in einen rechnerischen
|
/// Wandelt eine Notenangabe mit optionaler Tendenz ("3+", "2-") in einen rechnerischen
|
||||||
/// Notenwert um. Tendenzen verschieben um ein Drittel in Richtung der besseren Note
|
/// Notenwert um. Tendenzen verschieben um ein Drittel in Richtung der besseren Note
|
||||||
/// (z.B. "3+" → 2,67, "2-" → 2,33) — der in deutschen Notensystemen übliche Drittelabstand.
|
/// (z.B. "3+" → 2,67, "2-" → 2,33) — der in deutschen Notensystemen übliche Drittelabstand.
|
||||||
private static double? ParseGradeValue(string grade)
|
public static double? ParseGradeValue(string grade)
|
||||||
{
|
{
|
||||||
var trimmed = grade.Trim();
|
var trimmed = grade.Trim();
|
||||||
if (trimmed.Length == 0) return null;
|
if (trimmed.Length == 0) return null;
|
||||||
@@ -132,6 +132,18 @@ public class GradingService
|
|||||||
List<(string Grade, double Weight)> participationGrades,
|
List<(string Grade, double Weight)> participationGrades,
|
||||||
List<(string Grade, double Weight)> otherGrades,
|
List<(string Grade, double Weight)> otherGrades,
|
||||||
GradingScheme scheme, GradingSystem system, RoundingRule rounding)
|
GradingScheme scheme, GradingSystem system, RoundingRule rounding)
|
||||||
|
{
|
||||||
|
var weighted = CalculateReportGradeValue(examGrades, participationGrades, otherGrades, scheme);
|
||||||
|
return weighted is null ? null : RoundToGrade(weighted.Value, system, rounding);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wie <see cref="CalculateReportGrade"/>, liefert aber den ungerundeten gewichteten Wert —
|
||||||
|
/// für Ansichten, die zeigen sollen, wie knapp eine Note zwischen zwei Stufen liegt.
|
||||||
|
public double? CalculateReportGradeValue(
|
||||||
|
List<(string Grade, double Weight)> examGrades,
|
||||||
|
List<(string Grade, double Weight)> participationGrades,
|
||||||
|
List<(string Grade, double Weight)> otherGrades,
|
||||||
|
GradingScheme scheme)
|
||||||
{
|
{
|
||||||
var buckets = new List<(double Avg, double Percent)>();
|
var buckets = new List<(double Avg, double Percent)>();
|
||||||
if (examGrades.Count > 0) buckets.Add((WeightedAverage(examGrades), scheme.ExamsPercent));
|
if (examGrades.Count > 0) buckets.Add((WeightedAverage(examGrades), scheme.ExamsPercent));
|
||||||
@@ -141,8 +153,7 @@ public class GradingService
|
|||||||
var totalPercent = buckets.Sum(b => b.Percent);
|
var totalPercent = buckets.Sum(b => b.Percent);
|
||||||
if (buckets.Count == 0 || totalPercent <= 0) return null;
|
if (buckets.Count == 0 || totalPercent <= 0) return null;
|
||||||
|
|
||||||
var weighted = buckets.Sum(b => b.Avg * b.Percent) / totalPercent;
|
return buckets.Sum(b => b.Avg * b.Percent) / totalPercent;
|
||||||
return RoundToGrade(weighted, system, rounding);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ public enum SchoolYearPeriodKind { FullYear, H1, H2 }
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static class GroupMembershipService
|
public static class GroupMembershipService
|
||||||
{
|
{
|
||||||
|
/// <summary>Förderschüler ist, wer markiert ist oder in einer differenzierten Gruppe das
|
||||||
|
/// Förderniveau hat.</summary>
|
||||||
|
public static bool IsSupportStudent(GroupMembership? membership) =>
|
||||||
|
membership is { } m && (m.IsSupportStudent || m.Niveau == Niveau.Foerder);
|
||||||
|
|
||||||
public static bool IsActiveOn(GroupMembership membership, DateOnly date)
|
public static bool IsActiveOn(GroupMembership membership, DateOnly date)
|
||||||
{
|
{
|
||||||
if (membership.JoinedAt is { } joinedAt && date < joinedAt) return false;
|
if (membership.JoinedAt is { } joinedAt && date < joinedAt) return false;
|
||||||
|
|||||||
@@ -80,6 +80,7 @@ public sealed class GroupRolloverService(
|
|||||||
JoinedAt = targetStart,
|
JoinedAt = targetStart,
|
||||||
LeftAt = null,
|
LeftAt = null,
|
||||||
Niveau = membership.Niveau,
|
Niveau = membership.Niveau,
|
||||||
|
IsSupportStudent = membership.IsSupportStudent,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ public class PersonalDataExportService(
|
|||||||
IExamResultRepository examResults,
|
IExamResultRepository examResults,
|
||||||
IParticipationRepository participation,
|
IParticipationRepository participation,
|
||||||
IDocumentationRepository documentation,
|
IDocumentationRepository documentation,
|
||||||
ISeatingPlanRepository seatingPlans)
|
ISeatingPlanRepository seatingPlans,
|
||||||
|
IStudentGroupPlanRepository? studentGroupPlans = null)
|
||||||
{
|
{
|
||||||
public string ExportAsJson(Guid studentId)
|
public string ExportAsJson(Guid studentId)
|
||||||
{
|
{
|
||||||
@@ -56,6 +57,16 @@ public class PersonalDataExportService(
|
|||||||
Platz = a.Column + 1,
|
Platz = a.Column + 1,
|
||||||
}))
|
}))
|
||||||
.ToList(),
|
.ToList(),
|
||||||
|
GespeicherteGruppeneinteilungen = (studentGroupPlans?.GetByStudent(studentId) ?? [])
|
||||||
|
.SelectMany(plan => plan.Groups.Select((subgroup, index) => new
|
||||||
|
{
|
||||||
|
Einteilung = plan.Name,
|
||||||
|
Gruppe = index + 1,
|
||||||
|
Enthalten = subgroup.StudentIds.Contains(studentId),
|
||||||
|
}))
|
||||||
|
.Where(entry => entry.Enthalten)
|
||||||
|
.Select(entry => new { entry.Einteilung, entry.Gruppe })
|
||||||
|
.ToList(),
|
||||||
};
|
};
|
||||||
|
|
||||||
return JsonSerializer.Serialize(dto, new JsonSerializerOptions
|
return JsonSerializer.Serialize(dto, new JsonSerializerOptions
|
||||||
|
|||||||
@@ -61,6 +61,15 @@ public sealed class ChangeHookMatrixTests
|
|||||||
return (grade.Id, () => repo.Delete(grade.Id));
|
return (grade.Id, () => repo.Delete(grade.Id));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
yield return Case("InterimGrade", nameof(InterimGrade), db =>
|
||||||
|
{
|
||||||
|
var repo = new InterimGradeRepository(db);
|
||||||
|
var grade = new InterimGrade { StudentId = Guid.NewGuid(), GroupId = Guid.NewGuid(),
|
||||||
|
Date = new DateOnly(2025, 11, 12), Occasion = "Sprechtag", OverallValue = "3" };
|
||||||
|
repo.Save(grade);
|
||||||
|
return (grade.Id, () => repo.Delete(grade.Id));
|
||||||
|
});
|
||||||
|
|
||||||
yield return Case("Unit", nameof(Unit), db =>
|
yield return Case("Unit", nameof(Unit), db =>
|
||||||
{
|
{
|
||||||
var repo = new UnitRepository(db);
|
var repo = new UnitRepository(db);
|
||||||
|
|||||||
@@ -77,4 +77,26 @@ public sealed class ChangeHookTests
|
|||||||
Assert.Equal("Save", call.Operation);
|
Assert.Equal("Save", call.Operation);
|
||||||
Assert.Same(state, call.Payload);
|
Assert.Same(state, call.Payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DashboardWarningSnoozeRepository_Save_LoestOnChangeAus()
|
||||||
|
{
|
||||||
|
using var db = NewInMemoryContext();
|
||||||
|
var calls = new List<(string EntityType, string EntityId, string Operation, object? Payload)>();
|
||||||
|
db.OnChange = (type, id, op, payload) => calls.Add((type, id, op, payload));
|
||||||
|
var repo = new DashboardWarningSnoozeRepository(db);
|
||||||
|
var studentId = Guid.NewGuid();
|
||||||
|
var snooze = new DashboardWarningSnooze
|
||||||
|
{
|
||||||
|
StudentId = studentId, WarningTag = "Absentismus", SnoozedUntil = new DateOnly(2026, 10, 12),
|
||||||
|
};
|
||||||
|
|
||||||
|
repo.Save(snooze);
|
||||||
|
|
||||||
|
var call = Assert.Single(calls);
|
||||||
|
Assert.Equal(nameof(DashboardWarningSnooze), call.EntityType);
|
||||||
|
Assert.Equal(DashboardWarningSnooze.IdFor(studentId, "Absentismus").ToString(), call.EntityId);
|
||||||
|
Assert.Equal("Save", call.Operation);
|
||||||
|
Assert.Same(snooze, call.Payload);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -121,7 +121,7 @@ public sealed class LiteDbContextTests
|
|||||||
using var temp = new TempDatabase();
|
using var temp = new TempDatabase();
|
||||||
using var context = new LiteDbContext(temp.Path);
|
using var context = new LiteDbContext(temp.Path);
|
||||||
|
|
||||||
Assert.Equal(6, context.SchemaVersion);
|
Assert.Equal(7, context.SchemaVersion);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -132,7 +132,30 @@ public sealed class LiteDbContextTests
|
|||||||
|
|
||||||
using var second = new LiteDbContext(temp.Path);
|
using var second = new LiteDbContext(temp.Path);
|
||||||
|
|
||||||
Assert.Equal(6, second.SchemaVersion);
|
Assert.Equal(7, second.SchemaVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MigrateDashboardWarningSnoozeIds_SchluesseltLokaleEintraegeAufAbgeleiteteIdUm()
|
||||||
|
{
|
||||||
|
using var temp = new TempDatabase();
|
||||||
|
var studentId = Guid.NewGuid();
|
||||||
|
|
||||||
|
using (var legacy = new LiteDatabase(temp.Path))
|
||||||
|
{
|
||||||
|
legacy.GetCollection<BsonDocument>("meta").Upsert(new BsonDocument { ["_id"] = 1, ["SchemaVersion"] = 6 });
|
||||||
|
legacy.GetCollection<DashboardWarningSnooze>("dashboard_warning_snoozes").Insert(new DashboardWarningSnooze
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(), StudentId = studentId, WarningTag = "Verspätungen",
|
||||||
|
SnoozedUntil = new DateOnly(2026, 10, 12),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
using var context = new LiteDbContext(temp.Path);
|
||||||
|
|
||||||
|
var snooze = Assert.Single(context.DashboardWarningSnoozes.FindAll());
|
||||||
|
Assert.Equal(DashboardWarningSnooze.IdFor(studentId, "Verspätungen"), snooze.Id);
|
||||||
|
Assert.Equal(new DateOnly(2026, 10, 12), snooze.SnoozedUntil);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -8,6 +8,72 @@ public sealed class RepositoryTests
|
|||||||
{
|
{
|
||||||
private static LiteDbContext NewInMemoryContext() => new(new MemoryStream());
|
private static LiteDbContext NewInMemoryContext() => new(new MemoryStream());
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StudentGroupPlanRepository_SpeichertEinteilungUndLoeschtSieMitDerLerngruppe()
|
||||||
|
{
|
||||||
|
using var db = NewInMemoryContext();
|
||||||
|
var group = new LearningGroup { Name = "8a" };
|
||||||
|
new GroupRepository(db).Save(group);
|
||||||
|
var studentIds = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
|
||||||
|
var plan = new StudentGroupPlan
|
||||||
|
{
|
||||||
|
GroupId = group.Id,
|
||||||
|
Name = " Projektwoche ",
|
||||||
|
Groups =
|
||||||
|
[
|
||||||
|
new StudentGroupPlanGroup { StudentIds = [studentIds[0], studentIds[1]] },
|
||||||
|
new StudentGroupPlanGroup { StudentIds = [studentIds[2]] },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
var changes = new List<(string Type, string Operation)>();
|
||||||
|
db.OnChange = (type, _, operation, _) => changes.Add((type, operation));
|
||||||
|
var repo = new StudentGroupPlanRepository(db);
|
||||||
|
|
||||||
|
repo.Save(plan);
|
||||||
|
Assert.Equal("Projektwoche", repo.GetById(plan.Id)?.Name);
|
||||||
|
Assert.Equal(studentIds[2], repo.GetByGroup(group.Id).Single().Groups[1].StudentIds.Single());
|
||||||
|
Assert.Equal(plan.Id, Assert.Single(repo.GetByStudent(studentIds[0])).Id);
|
||||||
|
Assert.Contains((nameof(StudentGroupPlan), "Save"), changes);
|
||||||
|
|
||||||
|
var student = new Student { Id = studentIds[0], FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var students = new StudentRepository(db);
|
||||||
|
students.Save(student);
|
||||||
|
Assert.Throws<InvalidOperationException>(() => students.Delete(student.Id));
|
||||||
|
|
||||||
|
new GroupRepository(db).Delete(group.Id);
|
||||||
|
Assert.Empty(repo.GetByGroup(group.Id));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StudentGroupPlanRepository_VerhindertDoppelteSchuelerUndNamen()
|
||||||
|
{
|
||||||
|
using var db = NewInMemoryContext();
|
||||||
|
var group = new LearningGroup { Name = "8a" };
|
||||||
|
new GroupRepository(db).Save(group);
|
||||||
|
var repo = new StudentGroupPlanRepository(db);
|
||||||
|
var studentId = Guid.NewGuid();
|
||||||
|
Assert.Throws<InvalidOperationException>(() => repo.Save(new StudentGroupPlan
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Name = "Doppelt",
|
||||||
|
Groups =
|
||||||
|
[
|
||||||
|
new StudentGroupPlanGroup { StudentIds = [studentId] },
|
||||||
|
new StudentGroupPlanGroup { StudentIds = [studentId] },
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
|
||||||
|
repo.Save(new StudentGroupPlan
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Name = "Projektwoche",
|
||||||
|
Groups = [new StudentGroupPlanGroup { StudentIds = [studentId] }],
|
||||||
|
});
|
||||||
|
Assert.Throws<InvalidOperationException>(() => repo.Save(new StudentGroupPlan
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Name = "projektwoche",
|
||||||
|
Groups = [new StudentGroupPlanGroup()],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
// ── StudentRepository ─────────────────────────────────────────────────────
|
// ── StudentRepository ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -1338,4 +1404,39 @@ public sealed class RepositoryTests
|
|||||||
|
|
||||||
Assert.Null(repo.GetById(extra.Id));
|
Assert.Null(repo.GetById(extra.Id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DocumentationRepository_GetByStudent_FindetGemeinsamenEintragBeiAllenBeteiligten()
|
||||||
|
{
|
||||||
|
using var db = NewInMemoryContext();
|
||||||
|
var repo = new DocumentationRepository(db);
|
||||||
|
Guid anna = Guid.NewGuid(), ben = Guid.NewGuid(), cem = Guid.NewGuid();
|
||||||
|
var shared = new Documentation
|
||||||
|
{
|
||||||
|
StudentId = anna, AdditionalStudentIds = [ben], Title = "Konflikt", Type = DocumentationType.Incident,
|
||||||
|
};
|
||||||
|
repo.Save(shared);
|
||||||
|
|
||||||
|
Assert.Equal(shared.Id, Assert.Single(repo.GetByStudent(anna)).Id);
|
||||||
|
Assert.Equal(shared.Id, Assert.Single(repo.GetByStudent(ben)).Id);
|
||||||
|
Assert.Empty(repo.GetByStudent(cem));
|
||||||
|
Assert.Single(repo.GetByStudentAndType(ben, DocumentationType.Incident));
|
||||||
|
Assert.Empty(repo.GetByStudentAndType(ben, DocumentationType.Conversation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StudentRepository_GetReferenceSummary_ZaehltAuchGemeinsameDokumentation()
|
||||||
|
{
|
||||||
|
using var db = NewInMemoryContext();
|
||||||
|
var students = new StudentRepository(db);
|
||||||
|
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
|
||||||
|
students.Save(ben);
|
||||||
|
new DocumentationRepository(db).Save(new Documentation
|
||||||
|
{
|
||||||
|
StudentId = Guid.NewGuid(), AdditionalStudentIds = [ben.Id], Title = "Konflikt",
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.Equal(1, students.GetReferenceSummary(ben.Id).DocumentationEntries);
|
||||||
|
Assert.Throws<InvalidOperationException>(() => students.Delete(ben.Id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -41,12 +41,14 @@ public class LiteDbContext : IDisposable
|
|||||||
public ILiteCollection<Student> Students => _db.GetCollection<Student>("students");
|
public ILiteCollection<Student> Students => _db.GetCollection<Student>("students");
|
||||||
public ILiteCollection<LearningGroup> Groups => _db.GetCollection<LearningGroup>("groups");
|
public ILiteCollection<LearningGroup> Groups => _db.GetCollection<LearningGroup>("groups");
|
||||||
public ILiteCollection<SeatingPlan> SeatingPlans => _db.GetCollection<SeatingPlan>("seating_plans");
|
public ILiteCollection<SeatingPlan> SeatingPlans => _db.GetCollection<SeatingPlan>("seating_plans");
|
||||||
|
public ILiteCollection<StudentGroupPlan> StudentGroupPlans => _db.GetCollection<StudentGroupPlan>("student_group_plans");
|
||||||
public ILiteCollection<GroupMembership> Memberships => _db.GetCollection<GroupMembership>("group_memberships");
|
public ILiteCollection<GroupMembership> Memberships => _db.GetCollection<GroupMembership>("group_memberships");
|
||||||
public ILiteCollection<Exam> Exams => _db.GetCollection<Exam>("exams");
|
public ILiteCollection<Exam> Exams => _db.GetCollection<Exam>("exams");
|
||||||
public ILiteCollection<ExamResult> ExamResults => _db.GetCollection<ExamResult>("exam_results");
|
public ILiteCollection<ExamResult> ExamResults => _db.GetCollection<ExamResult>("exam_results");
|
||||||
public ILiteCollection<Grade> Grades => _db.GetCollection<Grade>("grades");
|
public ILiteCollection<Grade> Grades => _db.GetCollection<Grade>("grades");
|
||||||
public ILiteCollection<GradingScheme> GradingSchemes => _db.GetCollection<GradingScheme>("grading_schemes");
|
public ILiteCollection<GradingScheme> GradingSchemes => _db.GetCollection<GradingScheme>("grading_schemes");
|
||||||
public ILiteCollection<ReportGrade> ReportGrades => _db.GetCollection<ReportGrade>("report_grades");
|
public ILiteCollection<ReportGrade> ReportGrades => _db.GetCollection<ReportGrade>("report_grades");
|
||||||
|
public ILiteCollection<InterimGrade> InterimGrades => _db.GetCollection<InterimGrade>("interim_grades");
|
||||||
public ILiteCollection<GradingKeyTemplate> GradingKeyTemplates => _db.GetCollection<GradingKeyTemplate>("grading_key_templates");
|
public ILiteCollection<GradingKeyTemplate> GradingKeyTemplates => _db.GetCollection<GradingKeyTemplate>("grading_key_templates");
|
||||||
public ILiteCollection<Unit> Units => _db.GetCollection<Unit>("units");
|
public ILiteCollection<Unit> Units => _db.GetCollection<Unit>("units");
|
||||||
public ILiteCollection<Lesson> Lessons => _db.GetCollection<Lesson>("lessons");
|
public ILiteCollection<Lesson> Lessons => _db.GetCollection<Lesson>("lessons");
|
||||||
@@ -76,6 +78,7 @@ public class LiteDbContext : IDisposable
|
|||||||
public ILiteCollection<UntisHubJobState> UntisHubJobStates => _db.GetCollection<UntisHubJobState>("untis_hub_job_states");
|
public ILiteCollection<UntisHubJobState> UntisHubJobStates => _db.GetCollection<UntisHubJobState>("untis_hub_job_states");
|
||||||
public ILiteCollection<UntisStudentRosterCacheEntry> UntisStudentRosterCache => _db.GetCollection<UntisStudentRosterCacheEntry>("untis_student_roster_cache");
|
public ILiteCollection<UntisStudentRosterCacheEntry> UntisStudentRosterCache => _db.GetCollection<UntisStudentRosterCacheEntry>("untis_student_roster_cache");
|
||||||
public ILiteCollection<AnnualPlanEvent> AnnualPlanEvents => _db.GetCollection<AnnualPlanEvent>("annual_plan_events");
|
public ILiteCollection<AnnualPlanEvent> AnnualPlanEvents => _db.GetCollection<AnnualPlanEvent>("annual_plan_events");
|
||||||
|
public ILiteCollection<DashboardWarningSnooze> DashboardWarningSnoozes => _db.GetCollection<DashboardWarningSnooze>("dashboard_warning_snoozes");
|
||||||
public ILiteCollection<TrashedItem> TrashedItems => _db.GetCollection<TrashedItem>("trash");
|
public ILiteCollection<TrashedItem> TrashedItems => _db.GetCollection<TrashedItem>("trash");
|
||||||
|
|
||||||
public void Checkpoint() => _db.Checkpoint();
|
public void Checkpoint() => _db.Checkpoint();
|
||||||
@@ -112,6 +115,9 @@ public class LiteDbContext : IDisposable
|
|||||||
foreach (var reportGrade in ReportGrades.Find(g => g.GroupId == id).ToList())
|
foreach (var reportGrade in ReportGrades.Find(g => g.GroupId == id).ToList())
|
||||||
ReportGrades.Delete(reportGrade.Id);
|
ReportGrades.Delete(reportGrade.Id);
|
||||||
|
|
||||||
|
foreach (var interimGrade in InterimGrades.Find(g => g.GroupId == id).ToList())
|
||||||
|
InterimGrades.Delete(interimGrade.Id);
|
||||||
|
|
||||||
foreach (var scheme in GradingSchemes.Find(s => s.GroupId == id).ToList())
|
foreach (var scheme in GradingSchemes.Find(s => s.GroupId == id).ToList())
|
||||||
GradingSchemes.Delete(scheme.Id);
|
GradingSchemes.Delete(scheme.Id);
|
||||||
|
|
||||||
@@ -140,6 +146,8 @@ public class LiteDbContext : IDisposable
|
|||||||
|
|
||||||
foreach (var plan in SeatingPlans.Find(p => p.GroupId == id).ToList())
|
foreach (var plan in SeatingPlans.Find(p => p.GroupId == id).ToList())
|
||||||
SeatingPlans.Delete(plan.Id);
|
SeatingPlans.Delete(plan.Id);
|
||||||
|
foreach (var plan in StudentGroupPlans.Find(p => p.GroupId == id).ToList())
|
||||||
|
StudentGroupPlans.Delete(plan.Id);
|
||||||
|
|
||||||
// Dokumentation und Arbeitszeit sind historische Nachweise. Sie bleiben erhalten,
|
// Dokumentation und Arbeitszeit sind historische Nachweise. Sie bleiben erhalten,
|
||||||
// werden aber von der nicht mehr existierenden Lerngruppe entkoppelt.
|
// werden aber von der nicht mehr existierenden Lerngruppe entkoppelt.
|
||||||
@@ -273,9 +281,31 @@ public class LiteDbContext : IDisposable
|
|||||||
MigrateCompetencyReferences();
|
MigrateCompetencyReferences();
|
||||||
version = 6;
|
version = 6;
|
||||||
}
|
}
|
||||||
|
if (version < 7)
|
||||||
|
{
|
||||||
|
MigrateDashboardWarningSnoozeIds();
|
||||||
|
version = 7;
|
||||||
|
}
|
||||||
WriteSchemaVersion(version);
|
WriteSchemaVersion(version);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// DashboardWarningSnooze wird seit Schema 7 synchronisiert und braucht dafür eine aus
|
||||||
|
/// (StudentId, WarningTag) abgeleitete Id (siehe DashboardWarningSnooze.IdFor). Vorher lokal
|
||||||
|
/// angelegte Einträge mit zufälliger Id werden umgeschlüsselt, sonst kollidierte ein
|
||||||
|
/// eingehender Sync-Datensatz für dasselbe Paar am Unique-Index ux_student_tag.
|
||||||
|
private void MigrateDashboardWarningSnoozeIds()
|
||||||
|
{
|
||||||
|
var snoozes = DashboardWarningSnoozes;
|
||||||
|
foreach (var snooze in snoozes.FindAll().ToList())
|
||||||
|
{
|
||||||
|
var id = DashboardWarningSnooze.IdFor(snooze.StudentId, snooze.WarningTag);
|
||||||
|
if (snooze.Id == id) continue;
|
||||||
|
snoozes.Delete(snooze.Id);
|
||||||
|
snooze.Id = id;
|
||||||
|
snoozes.Upsert(snooze);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private int ReadSchemaVersion()
|
private int ReadSchemaVersion()
|
||||||
{
|
{
|
||||||
var meta = _db.GetCollection<BsonDocument>("meta").FindById(1);
|
var meta = _db.GetCollection<BsonDocument>("meta").FindById(1);
|
||||||
@@ -636,6 +666,7 @@ public class LiteDbContext : IDisposable
|
|||||||
Groups.EnsureIndex(x => x.SchoolYear);
|
Groups.EnsureIndex(x => x.SchoolYear);
|
||||||
Groups.EnsureIndex(x => x.IsActive);
|
Groups.EnsureIndex(x => x.IsActive);
|
||||||
SeatingPlans.EnsureIndex(x => x.GroupId);
|
SeatingPlans.EnsureIndex(x => x.GroupId);
|
||||||
|
StudentGroupPlans.EnsureIndex(x => x.GroupId);
|
||||||
Memberships.EnsureIndex(x => x.StudentId);
|
Memberships.EnsureIndex(x => x.StudentId);
|
||||||
Memberships.EnsureIndex(x => x.GroupId);
|
Memberships.EnsureIndex(x => x.GroupId);
|
||||||
Memberships.EnsureIndex("ux_student_group",
|
Memberships.EnsureIndex("ux_student_group",
|
||||||
@@ -654,6 +685,8 @@ public class LiteDbContext : IDisposable
|
|||||||
ReportGrades.EnsureIndex(x => x.StudentId);
|
ReportGrades.EnsureIndex(x => x.StudentId);
|
||||||
ReportGrades.EnsureIndex("ux_student_group_period",
|
ReportGrades.EnsureIndex("ux_student_group_period",
|
||||||
BsonExpression.Create("STRING($.StudentId) + ':' + STRING($.GroupId) + ':' + $.Period"), unique: true);
|
BsonExpression.Create("STRING($.StudentId) + ':' + STRING($.GroupId) + ':' + $.Period"), unique: true);
|
||||||
|
InterimGrades.EnsureIndex(x => x.GroupId);
|
||||||
|
InterimGrades.EnsureIndex(x => x.StudentId);
|
||||||
GradingKeyTemplates.EnsureIndex(x => x.GradingSystem);
|
GradingKeyTemplates.EnsureIndex(x => x.GradingSystem);
|
||||||
Units.EnsureIndex(x => x.GroupId);
|
Units.EnsureIndex(x => x.GroupId);
|
||||||
Lessons.EnsureIndex(x => x.UnitId);
|
Lessons.EnsureIndex(x => x.UnitId);
|
||||||
@@ -694,6 +727,8 @@ public class LiteDbContext : IDisposable
|
|||||||
UntisStudentRosterCache.EnsureIndex(x => x.ClassName);
|
UntisStudentRosterCache.EnsureIndex(x => x.ClassName);
|
||||||
UntisCacheFetchStates.EnsureIndex("ux_class_kind",
|
UntisCacheFetchStates.EnsureIndex("ux_class_kind",
|
||||||
BsonExpression.Create("STRING($.ClassName) + ':' + STRING($.Kind)"), unique: true);
|
BsonExpression.Create("STRING($.ClassName) + ':' + STRING($.Kind)"), unique: true);
|
||||||
|
DashboardWarningSnoozes.EnsureIndex("ux_student_tag",
|
||||||
|
BsonExpression.Create("STRING($.StudentId) + ':' + STRING($.WarningTag)"), unique: true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose() => _db.Dispose();
|
public void Dispose() => _db.Dispose();
|
||||||
|
|||||||
@@ -32,9 +32,12 @@ public class StudentRepository(LiteDbContext db) : IStudentRepository
|
|||||||
db.Memberships.Count(m => m.StudentId == studentId),
|
db.Memberships.Count(m => m.StudentId == studentId),
|
||||||
db.ExamResults.Count(r => r.StudentId == studentId),
|
db.ExamResults.Count(r => r.StudentId == studentId),
|
||||||
db.Grades.Count(g => g.StudentId == studentId),
|
db.Grades.Count(g => g.StudentId == studentId),
|
||||||
db.ReportGrades.Count(g => g.StudentId == studentId),
|
// Zwischenstände sind vorläufige Zeugnisnoten und zählen hier mit.
|
||||||
|
db.ReportGrades.Count(g => g.StudentId == studentId) + db.InterimGrades.Count(g => g.StudentId == studentId),
|
||||||
db.ParticipationEntries.Count(e => e.StudentId == studentId),
|
db.ParticipationEntries.Count(e => e.StudentId == studentId),
|
||||||
db.Documentation.Count(d => d.StudentId == studentId));
|
db.Documentation.FindAll().Count(d => d.Concerns(studentId)),
|
||||||
|
db.StudentGroupPlans.FindAll().Count(plan =>
|
||||||
|
plan.Groups.Any(group => group.StudentIds.Contains(studentId))));
|
||||||
public void Save(Student s)
|
public void Save(Student s)
|
||||||
{
|
{
|
||||||
s.ExternalIds ??= [];
|
s.ExternalIds ??= [];
|
||||||
@@ -328,6 +331,27 @@ public class GradingSchemeRepository(LiteDbContext db) : IGradingSchemeRepositor
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class InterimGradeRepository(LiteDbContext db) : IInterimGradeRepository
|
||||||
|
{
|
||||||
|
public List<InterimGrade> GetByGroup(Guid groupId) => db.InterimGrades.Find(g => g.GroupId == groupId).ToList();
|
||||||
|
public List<InterimGrade> GetByStudentAndGroup(Guid studentId, Guid groupId) =>
|
||||||
|
db.InterimGrades.Find(g => g.StudentId == studentId && g.GroupId == groupId).ToList();
|
||||||
|
public void Save(InterimGrade g)
|
||||||
|
{
|
||||||
|
ArchivedGroupWriteGuard.EnsureActive(db, g.GroupId);
|
||||||
|
g.UpdatedAt = DateTime.UtcNow;
|
||||||
|
db.InterimGrades.Upsert(g);
|
||||||
|
db.OnChange?.Invoke(nameof(InterimGrade), g.Id.ToString(), "Save", g);
|
||||||
|
}
|
||||||
|
public void Delete(Guid id)
|
||||||
|
{
|
||||||
|
if (db.InterimGrades.FindById(id) is { } grade)
|
||||||
|
ArchivedGroupWriteGuard.EnsureActive(db, grade.GroupId);
|
||||||
|
db.InterimGrades.Delete(id);
|
||||||
|
db.OnChange?.Invoke(nameof(InterimGrade), id.ToString(), "Delete", null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public class ReportGradeRepository(LiteDbContext db) : IReportGradeRepository
|
public class ReportGradeRepository(LiteDbContext db) : IReportGradeRepository
|
||||||
{
|
{
|
||||||
public List<ReportGrade> GetByGroup(Guid groupId) => db.ReportGrades.Find(r => r.GroupId == groupId).ToList();
|
public List<ReportGrade> GetByGroup(Guid groupId) => db.ReportGrades.Find(r => r.GroupId == groupId).ToList();
|
||||||
@@ -415,10 +439,13 @@ public class LessonRepository(LiteDbContext db) : ILessonRepository
|
|||||||
|
|
||||||
public class DocumentationRepository(LiteDbContext db) : IDocumentationRepository
|
public class DocumentationRepository(LiteDbContext db) : IDocumentationRepository
|
||||||
{
|
{
|
||||||
|
// Filter auf AdditionalStudentIds bewusst im Speicher statt als LiteDB-Ausdruck — die Menge
|
||||||
|
// an Dokumentation pro Lehrkraft ist klein, und so gilt exakt dieselbe Regel wie Documentation.Concerns.
|
||||||
public List<Documentation> GetByStudent(Guid id) =>
|
public List<Documentation> GetByStudent(Guid id) =>
|
||||||
db.Documentation.Find(d => d.StudentId == id && !d.IsDeleted).OrderByDescending(d => d.Date).ToList();
|
db.Documentation.Find(d => !d.IsDeleted).Where(d => d.Concerns(id))
|
||||||
|
.OrderByDescending(d => d.Date).ToList();
|
||||||
public List<Documentation> GetByStudentAndType(Guid sid, DocumentationType type) =>
|
public List<Documentation> GetByStudentAndType(Guid sid, DocumentationType type) =>
|
||||||
db.Documentation.Find(d => d.StudentId == sid && d.Type == type && !d.IsDeleted)
|
db.Documentation.Find(d => d.Type == type && !d.IsDeleted).Where(d => d.Concerns(sid))
|
||||||
.OrderByDescending(d => d.Date).ToList();
|
.OrderByDescending(d => d.Date).ToList();
|
||||||
public List<Documentation> GetAll() =>
|
public List<Documentation> GetAll() =>
|
||||||
db.Documentation.Find(d => !d.IsDeleted).OrderByDescending(d => d.Date).ToList();
|
db.Documentation.Find(d => !d.IsDeleted).OrderByDescending(d => d.Date).ToList();
|
||||||
@@ -901,6 +928,19 @@ public class UntisCacheFetchStateRepository(LiteDbContext db) : IUntisCacheFetch
|
|||||||
public void Save(UntisCacheFetchState state) => db.UntisCacheFetchStates.Upsert(state);
|
public void Save(UntisCacheFetchState state) => db.UntisCacheFetchStates.Upsert(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class DashboardWarningSnoozeRepository(LiteDbContext db) : IDashboardWarningSnoozeRepository
|
||||||
|
{
|
||||||
|
public DashboardWarningSnooze? Get(Guid studentId, string warningTag) =>
|
||||||
|
db.DashboardWarningSnoozes.FindOne(s => s.StudentId == studentId && s.WarningTag == warningTag);
|
||||||
|
public List<DashboardWarningSnooze> GetAll() => db.DashboardWarningSnoozes.FindAll().ToList();
|
||||||
|
public void Save(DashboardWarningSnooze snooze)
|
||||||
|
{
|
||||||
|
snooze.Id = DashboardWarningSnooze.IdFor(snooze.StudentId, snooze.WarningTag);
|
||||||
|
db.DashboardWarningSnoozes.Upsert(snooze);
|
||||||
|
db.OnChange?.Invoke(nameof(DashboardWarningSnooze), snooze.Id.ToString(), "Save", snooze);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public class UntisHubJobStateRepository(LiteDbContext db) : IUntisHubJobStateRepository
|
public class UntisHubJobStateRepository(LiteDbContext db) : IUntisHubJobStateRepository
|
||||||
{
|
{
|
||||||
public UntisHubJobState? Get(UntisHubJobKind kind, Guid? groupId) =>
|
public UntisHubJobState? Get(UntisHubJobKind kind, Guid? groupId) =>
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
|
||||||
|
namespace LehrerApp.Data.Repositories;
|
||||||
|
|
||||||
|
public class StudentGroupPlanRepository(LiteDbContext db) : IStudentGroupPlanRepository
|
||||||
|
{
|
||||||
|
public StudentGroupPlan? GetById(Guid id) => db.StudentGroupPlans.FindById(id);
|
||||||
|
|
||||||
|
public List<StudentGroupPlan> GetByGroup(Guid groupId) =>
|
||||||
|
db.StudentGroupPlans.Find(p => p.GroupId == groupId)
|
||||||
|
.OrderByDescending(p => p.UpdatedAt).ToList();
|
||||||
|
|
||||||
|
public List<StudentGroupPlan> GetByStudent(Guid studentId) =>
|
||||||
|
db.StudentGroupPlans.FindAll()
|
||||||
|
.Where(plan => plan.Groups.Any(group => group.StudentIds.Contains(studentId)))
|
||||||
|
.OrderByDescending(plan => plan.UpdatedAt).ToList();
|
||||||
|
|
||||||
|
public void Save(StudentGroupPlan plan)
|
||||||
|
{
|
||||||
|
if (db.Groups.FindById(plan.GroupId) is null)
|
||||||
|
throw new InvalidOperationException("Die zugehörige Lerngruppe existiert nicht.");
|
||||||
|
ArchivedGroupWriteGuard.EnsureActive(db, plan.GroupId);
|
||||||
|
plan.Name = plan.Name?.Trim() ?? "";
|
||||||
|
if (plan.Name.Length == 0)
|
||||||
|
throw new ArgumentException("Bitte einen Namen für die Gruppeneinteilung eingeben.");
|
||||||
|
plan.Groups ??= [];
|
||||||
|
if (plan.Groups.Count == 0)
|
||||||
|
throw new InvalidOperationException("Die Gruppeneinteilung enthält keine Gruppen.");
|
||||||
|
var ids = plan.Groups.SelectMany(g => g.StudentIds ?? []).ToList();
|
||||||
|
if (ids.Count != ids.Distinct().Count())
|
||||||
|
throw new InvalidOperationException("Ein Schüler darf nur in einer Gruppe stehen.");
|
||||||
|
if (db.StudentGroupPlans.Find(p => p.GroupId == plan.GroupId)
|
||||||
|
.Any(p => p.Id != plan.Id && string.Equals(p.Name, plan.Name, StringComparison.OrdinalIgnoreCase)))
|
||||||
|
throw new InvalidOperationException("Eine gespeicherte Einteilung mit diesem Namen gibt es bereits.");
|
||||||
|
|
||||||
|
if (db.StudentGroupPlans.FindById(plan.Id) is { } existing)
|
||||||
|
{
|
||||||
|
if (existing.GroupId != plan.GroupId)
|
||||||
|
throw new InvalidOperationException("Eine Gruppeneinteilung kann nicht in eine andere Lerngruppe verschoben werden.");
|
||||||
|
plan.CreatedAt = existing.CreatedAt;
|
||||||
|
}
|
||||||
|
plan.UpdatedAt = DateTime.UtcNow;
|
||||||
|
db.StudentGroupPlans.Upsert(plan);
|
||||||
|
db.OnChange?.Invoke(nameof(StudentGroupPlan), plan.Id.ToString(), "Save", plan);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Delete(Guid id)
|
||||||
|
{
|
||||||
|
if (db.StudentGroupPlans.FindById(id) is not { } plan) return;
|
||||||
|
ArchivedGroupWriteGuard.EnsureActive(db, plan.GroupId);
|
||||||
|
db.StudentGroupPlans.Delete(id);
|
||||||
|
db.OnChange?.Invoke(nameof(StudentGroupPlan), id.ToString(), "Delete", null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,38 @@ namespace LehrerApp.Desktop.Tests;
|
|||||||
|
|
||||||
public sealed class ClassTeacherViewModelsTests
|
public sealed class ClassTeacherViewModelsTests
|
||||||
{
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Früher gegangen", 2, 90)]
|
||||||
|
[InlineData("Vorzeitig verlassen", 0, 20)]
|
||||||
|
public void FruehesGehen_IstTeilfehlzeitUndImKalenderGesondertErkennbar(string reason, int periods, int minutes)
|
||||||
|
{
|
||||||
|
var date = new DateOnly(2026, 9, 3);
|
||||||
|
var row = new ClassAbsenceDaySummaryRow(date, "Müller Ada", 1, periods, minutes,
|
||||||
|
[], [], ["nicht entsch."], [reason], null, null, true);
|
||||||
|
|
||||||
|
Assert.True(row.IsEarlyDeparture);
|
||||||
|
Assert.False(row.CountsAsFullDay);
|
||||||
|
Assert.False(row.IsLate);
|
||||||
|
Assert.True(row.IsPartialAbsence);
|
||||||
|
var marker = Assert.Single(ClassTeacherDetailsViewModel.BuildDayEvents(date, [row], [], false));
|
||||||
|
Assert.Equal("G", marker.Code);
|
||||||
|
Assert.Equal("#C62828", marker.ColorHex);
|
||||||
|
Assert.Contains("Früher gegangen", marker.Tooltip);
|
||||||
|
Assert.Contains("Unentschuldigt", marker.Tooltip);
|
||||||
|
Assert.DoesNotContain("Ganzer Fehltag", marker.Tooltip);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Kalender_GanzeFehltageBehaltenEigenesKuerzel()
|
||||||
|
{
|
||||||
|
var date = new DateOnly(2026, 9, 3);
|
||||||
|
var row = new ClassAbsenceDaySummaryRow(date, "Müller Ada", 1, 6, 270,
|
||||||
|
[], [], ["nicht entsch."], ["Absent"], null, null, true);
|
||||||
|
var marker = Assert.Single(ClassTeacherDetailsViewModel.BuildDayEvents(date, [row], [], false));
|
||||||
|
Assert.Equal("U", marker.Code);
|
||||||
|
Assert.Contains("Ganzer Fehltag", marker.Tooltip);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Monatskalender_KodiertFehlzeitenUndBlendetHausaufgabenStandardmaessigAus()
|
public void Monatskalender_KodiertFehlzeitenUndBlendetHausaufgabenStandardmaessigAus()
|
||||||
{
|
{
|
||||||
@@ -32,7 +64,7 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
|
|
||||||
Assert.Equal(0, days.Count % 5);
|
Assert.Equal(0, days.Count % 5);
|
||||||
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "V");
|
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "V");
|
||||||
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "U");
|
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "T");
|
||||||
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "!");
|
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "!");
|
||||||
Assert.DoesNotContain(days.SelectMany(d => d.Events), e => e.Code == "H");
|
Assert.DoesNotContain(days.SelectMany(d => d.Events), e => e.Code == "H");
|
||||||
|
|
||||||
@@ -65,10 +97,10 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
Assert.Equal(30, days.Count);
|
Assert.Equal(30, days.Count);
|
||||||
Assert.False(days[0].HasSignal);
|
Assert.False(days[0].HasSignal);
|
||||||
Assert.Equal("1", days[0].DayNumber);
|
Assert.Equal("1", days[0].DayNumber);
|
||||||
Assert.Equal("U", days[2].SignalCode); // stärker als der parallele Klassenbucheintrag
|
Assert.Equal("T", days[2].SignalCode); // stärker als der parallele Klassenbucheintrag
|
||||||
Assert.True(days[2].IsToday);
|
Assert.True(days[2].IsToday);
|
||||||
Assert.Contains("Ada Müller", days[2].Tooltip);
|
Assert.Contains("Ada Müller", days[2].Tooltip);
|
||||||
Assert.Equal("E", days[3].SignalCode);
|
Assert.Equal("T", days[3].SignalCode);
|
||||||
Assert.False(days[4].HasSignal); // Hausaufgaben bleiben im Widget bewusst ausgeblendet
|
Assert.False(days[4].HasSignal); // Hausaufgaben bleiben im Widget bewusst ausgeblendet
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +119,7 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
var days = ClassTeacherOverviewViewModel.BuildCompactMonthDays(month, absences, [], month,
|
var days = ClassTeacherOverviewViewModel.BuildCompactMonthDays(month, absences, [], month,
|
||||||
"Ada Müller");
|
"Ada Müller");
|
||||||
|
|
||||||
Assert.Equal("U", days[2].SignalCode);
|
Assert.Equal("T", days[2].SignalCode);
|
||||||
Assert.False(days[3].HasSignal);
|
Assert.False(days[3].HasSignal);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,7 +139,7 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
|
|
||||||
Assert.True(drawing.ContentHeight > 0);
|
Assert.True(drawing.ContentHeight > 0);
|
||||||
Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "Ada Müller");
|
Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "Ada Müller");
|
||||||
Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "U");
|
Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "T");
|
||||||
Assert.DoesNotContain(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "E");
|
Assert.DoesNotContain(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "E");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -367,6 +399,24 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
Assert.False(andere.CountsAsFullDay);
|
Assert.False(andere.CountsAsFullDay);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GroupByStudentAndDay_ZweiFehlstundenBleibenTeilfehlzeit()
|
||||||
|
{
|
||||||
|
var entries = new[]
|
||||||
|
{
|
||||||
|
new UntisClassAbsenceEntryDto("Muster Max", 1, "6a", 20260824, 1, 45, "HED", "Che", null,
|
||||||
|
null, 1, null, true, null, 3, "nicht entsch.", false),
|
||||||
|
new UntisClassAbsenceEntryDto("Muster Max", 1, "6a", 20260824, 1, 45, "PAN", "Kunst", null,
|
||||||
|
null, 2, null, true, null, 4, "nicht entsch.", false),
|
||||||
|
};
|
||||||
|
|
||||||
|
var row = Assert.Single(ClassAbsenceDaySummaryRow.GroupByStudentAndDay(entries));
|
||||||
|
|
||||||
|
Assert.False(row.CountsAsFullDay);
|
||||||
|
Assert.True(row.IsPartialAbsence);
|
||||||
|
Assert.Equal("2 Fehlstunden", row.KindLabel);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void GroupByStudentAndDay_TrenntGleichenNamenAnUnterschiedlichenTagen()
|
public void GroupByStudentAndDay_TrenntGleichenNamenAnUnterschiedlichenTagen()
|
||||||
{
|
{
|
||||||
@@ -509,11 +559,14 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
termStart: new DateOnly(2026, 8, 1)));
|
termStart: new DateOnly(2026, 8, 1)));
|
||||||
|
|
||||||
Assert.True(row.HasYearSummary);
|
Assert.True(row.HasYearSummary);
|
||||||
Assert.Equal(2, row.YearAbsenceDayCount);
|
Assert.Equal(1, row.YearAbsenceDayCount);
|
||||||
Assert.Equal(1, row.YearUnexcusedDayCount);
|
Assert.Equal(1, row.YearUnexcusedDayCount);
|
||||||
Assert.Equal(10, row.YearAbsenceRatePercent);
|
Assert.Equal(2, row.YearAbsencePeriodCount);
|
||||||
Assert.Contains("10 %", row.YearSummaryLabel);
|
Assert.Equal(2, row.YearExcusedPeriodCount);
|
||||||
Assert.Contains("2 von 20", row.YearSummaryTooltip);
|
Assert.Equal(5, row.YearAbsenceRatePercent);
|
||||||
|
Assert.Contains("5 %", row.YearSummaryLabel);
|
||||||
|
Assert.Contains("1 von 20", row.YearSummaryTooltip);
|
||||||
|
Assert.Contains("2 Fehlstunden", row.YearSummaryTooltip);
|
||||||
Assert.Contains("seit 01.08.", row.YearSummaryTooltip);
|
Assert.Contains("seit 01.08.", row.YearSummaryTooltip);
|
||||||
Assert.Contains("1 unentschuldigt", row.YearSummaryTooltip);
|
Assert.Contains("1 unentschuldigt", row.YearSummaryTooltip);
|
||||||
}
|
}
|
||||||
@@ -577,24 +630,30 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void RosterBuild_UnentschuldigtUndVerspaetetZaehltAlsUnentschuldigtNichtAlsVerspaetung()
|
public void RosterBuild_UnentschuldigteFehlstundeZaehltNichtAlsGanzerFehltag()
|
||||||
{
|
{
|
||||||
// Wer unentschuldigt UND verspätet ist, bleibt der schwerwiegendere Fall (dieselbe
|
// Kernfall: Eine Schülerin fehlt aus Protest eine Unterrichtsstunde. Das bleibt
|
||||||
// Rangfolge wie AttentionRank/StatusKind/BuildTrend: Unentschuldigt vor Verspätet) — zählt
|
// unentschuldigt und score-relevant, darf im Zeugnis-/Jahresstand aber nicht als ganzer
|
||||||
// deshalb weiter voll in die Quote statt in YearLateDayCount zu verschwinden.
|
// unentschuldigter Fehltag erscheinen.
|
||||||
var students = new[] { Student(1001, "Ada Müller") };
|
var students = new[] { Student(1001, "Ada Müller") };
|
||||||
var yearAbsences = new[]
|
var yearAbsences = new[]
|
||||||
{
|
{
|
||||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10), "Müller Ada", 1001, 0, 60,
|
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10), "Müller Ada", 1001, 1, 45,
|
||||||
["Deu"], [1], ["nicht entsch."], ["Verspätung"], null, null, false),
|
["Deu"], [1], ["nicht entsch."], ["Absent"], "Aus Protest gegangen", null, false),
|
||||||
};
|
};
|
||||||
|
|
||||||
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [],
|
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [],
|
||||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1)));
|
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1)));
|
||||||
|
|
||||||
Assert.Equal(1, row.YearAbsenceDayCount);
|
Assert.Equal(0, row.YearAbsenceDayCount);
|
||||||
Assert.Equal(1, row.YearUnexcusedDayCount);
|
Assert.Equal(0, row.YearUnexcusedDayCount);
|
||||||
|
Assert.Equal(1, row.YearAbsencePeriodCount);
|
||||||
|
Assert.Equal(1, row.YearUnexcusedPeriodCount);
|
||||||
Assert.Equal(0, row.YearLateDayCount);
|
Assert.Equal(0, row.YearLateDayCount);
|
||||||
|
Assert.Equal(0, row.YearAbsenceRatePercent);
|
||||||
|
Assert.Contains("1 Fehlstunde", row.YearSummaryLabel);
|
||||||
|
Assert.Contains("1 unentschuldigt", row.YearSummaryTooltip);
|
||||||
|
Assert.Equal(0.5, row.PatternScore, precision: 10); // 1 von typischerweise 6 Stunden × Tagesgewicht 3
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -754,7 +813,8 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [], new DateOnly(2026, 8, 26),
|
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [], new DateOnly(2026, 8, 26),
|
||||||
yearAbsences, schoolDaysElapsed: 10));
|
yearAbsences, schoolDaysElapsed: 10));
|
||||||
|
|
||||||
Assert.Equal(1, row.YearAbsenceDayCount);
|
Assert.Equal(0, row.YearAbsenceDayCount);
|
||||||
|
Assert.Equal(2, row.YearAbsencePeriodCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -963,9 +1023,9 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
var absences = new[]
|
var absences = new[]
|
||||||
{
|
{
|
||||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 24), "Fehlt Cem", 1001, 1, 45,
|
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 24), "Fehlt Cem", 1001, 1, 45,
|
||||||
["Deu"], [1], ["nicht entsch."], ["Absent"], null, null, false),
|
["Deu"], [1], ["nicht entsch."], ["Absent"], null, null, true),
|
||||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 25), "Fehlt Cem", 1001, 1, 45,
|
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 25), "Fehlt Cem", 1001, 1, 45,
|
||||||
["Deu"], [1], ["nicht entsch."], ["Absent"], null, null, false),
|
["Deu"], [1], ["nicht entsch."], ["Absent"], null, null, true),
|
||||||
};
|
};
|
||||||
var names = new Dictionary<string, string> { [UntisNameMatching.NameKey("Fehlt Cem")] = "Cem Fehlt" };
|
var names = new Dictionary<string, string> { [UntisNameMatching.NameKey("Fehlt Cem")] = "Cem Fehlt" };
|
||||||
|
|
||||||
@@ -978,6 +1038,26 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
Assert.False(notice.CanCreateReminder);
|
Assert.False(notice.CanCreateReminder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetectLatePatterns_StundenweisesUnentschuldigtesFehlenBleibtEigeneWarnstufe()
|
||||||
|
{
|
||||||
|
var absences = new[]
|
||||||
|
{
|
||||||
|
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 21), "Protest Ada", 1001, 1, 45,
|
||||||
|
["Deu"], [2], ["nicht entsch."], ["Absent"], null, null, false),
|
||||||
|
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 24), "Protest Ada", 1001, 1, 45,
|
||||||
|
["Mat"], [4], ["nicht entsch."], ["Absent"], null, null, false),
|
||||||
|
};
|
||||||
|
var names = new Dictionary<string, string>
|
||||||
|
{ [UntisNameMatching.NameKey("Protest Ada")] = "Ada Protest" };
|
||||||
|
|
||||||
|
var notice = Assert.Single(ClassTeacherOverviewViewModel.DetectLatePatterns(
|
||||||
|
absences, names, sevenDayStart: new DateOnly(2026, 9, 20)));
|
||||||
|
|
||||||
|
Assert.Contains("stundenweise unentschuldigte Fehlzeiten", notice.Message);
|
||||||
|
Assert.Equal(ClassTeacherStatusKind.Warning, notice.Kind);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Aggregierte Klassenbuch-Kategorien (Feature-Idee 5) ──────────────────
|
// ── Aggregierte Klassenbuch-Kategorien (Feature-Idee 5) ──────────────────
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -1230,6 +1310,18 @@ public sealed class ClassTeacherViewModelsTests
|
|||||||
Assert.Empty(result);
|
Assert.Empty(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FilterAvailableDocumentation_BeruecksichtigtWeitereBeteiligte()
|
||||||
|
{
|
||||||
|
Guid ada = Guid.NewGuid(), ben = Guid.NewGuid();
|
||||||
|
var shared = new Documentation { StudentId = Guid.NewGuid(), AdditionalStudentIds = [ben] };
|
||||||
|
var vorgang = new Vorgang { StudentIds = [ada, ben] };
|
||||||
|
|
||||||
|
var result = ClassTeacherCasesViewModel.FilterAvailableDocumentation([shared], vorgang);
|
||||||
|
|
||||||
|
Assert.Equal(shared.Id, Assert.Single(result).Id);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Konfigurierbare Gewichtung + Dämpfung/Rückfall-Warnung nach geschlossenem Vorgang ─────────
|
// ── Konfigurierbare Gewichtung + Dämpfung/Rückfall-Warnung nach geschlossenem Vorgang ─────────
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using CommunityToolkit.Mvvm.Input;
|
||||||
using LehrerApp.Core.Models;
|
using LehrerApp.Core.Models;
|
||||||
using LehrerApp.Core.Services;
|
using LehrerApp.Core.Services;
|
||||||
using LehrerApp.Desktop.ViewModels;
|
using LehrerApp.Desktop.ViewModels;
|
||||||
@@ -83,6 +84,11 @@ public sealed class DashboardViewModelTests
|
|||||||
private static IEnumerable<AttentionItem> Items(DashboardViewModel vm, AttentionKind kind) =>
|
private static IEnumerable<AttentionItem> Items(DashboardViewModel vm, AttentionKind kind) =>
|
||||||
vm.Attention.Where(g => g.Kind == kind).SelectMany(g => g.Items);
|
vm.Attention.Where(g => g.Kind == kind).SelectMany(g => g.Items);
|
||||||
|
|
||||||
|
/// Entschärfte Warnungen stehen nicht in ihrer Art-Gruppe, sondern gesammelt in der
|
||||||
|
/// "Zurückgestellt"-Gruppe am Ende.
|
||||||
|
private static IEnumerable<AttentionItem> DeferredItems(DashboardViewModel vm) =>
|
||||||
|
vm.Attention.Where(g => g.IsDeferred).SelectMany(g => g.Items);
|
||||||
|
|
||||||
/// AttentionItem traegt fuer MissingTeachingTime kein eigenes Date-Feld (Title ist bereits der
|
/// AttentionItem traegt fuer MissingTeachingTime kein eigenes Date-Feld (Title ist bereits der
|
||||||
/// formatierte Anzeigetext) — das genaue Datum steckt im mitgegebenen Action-Parameter
|
/// formatierte Anzeigetext) — das genaue Datum steckt im mitgegebenen Action-Parameter
|
||||||
/// (derselbe MissingTeachingTimeItem, den auch der "Erfassen"-Dialog erhaelt).
|
/// (derselbe MissingTeachingTimeItem, den auch der "Erfassen"-Dialog erhaelt).
|
||||||
@@ -143,6 +149,7 @@ public sealed class DashboardViewModelTests
|
|||||||
FakeExams? exams = null, FakeResults? results = null, FakeGrades? grades = null,
|
FakeExams? exams = null, FakeResults? results = null, FakeGrades? grades = null,
|
||||||
FakeReportGrades? reportGrades = null, FakeMemberships? memberships = null,
|
FakeReportGrades? reportGrades = null, FakeMemberships? memberships = null,
|
||||||
FakeWorkTasks? tasks = null, FakeStudents? students = null, FakeDocumentation? documentation = null,
|
FakeWorkTasks? tasks = null, FakeStudents? students = null, FakeDocumentation? documentation = null,
|
||||||
|
FakeVorgangRepository? vorgaenge = null, FakeDashboardWarningSnoozeRepository? warningSnoozes = null,
|
||||||
DashboardSettingsService? dashboardSettings = null, FakeSchoolHolidays? schoolHolidays = null,
|
DashboardSettingsService? dashboardSettings = null, FakeSchoolHolidays? schoolHolidays = null,
|
||||||
FakeLessons? lessons = null, FakeSubstitutionEntries? substitutions = null,
|
FakeLessons? lessons = null, FakeSubstitutionEntries? substitutions = null,
|
||||||
FakeSessions? sessions = null, FakeEntries? entries = null,
|
FakeSessions? sessions = null, FakeEntries? entries = null,
|
||||||
@@ -157,6 +164,7 @@ public sealed class DashboardViewModelTests
|
|||||||
reportGrades ?? new FakeReportGrades(), memberships ?? new FakeMemberships([]),
|
reportGrades ?? new FakeReportGrades(), memberships ?? new FakeMemberships([]),
|
||||||
tasks ?? new FakeWorkTasks(), sessions ?? new FakeSessions([]), entries ?? new FakeEntries(),
|
tasks ?? new FakeWorkTasks(), sessions ?? new FakeSessions([]), entries ?? new FakeEntries(),
|
||||||
students ?? new FakeStudents([]), documentation ?? new FakeDocumentation(),
|
students ?? new FakeStudents([]), documentation ?? new FakeDocumentation(),
|
||||||
|
vorgaenge ?? new FakeVorgangRepository(), warningSnoozes ?? new FakeDashboardWarningSnoozeRepository(),
|
||||||
slots ?? new FakeTimetableSlots(), periodSchedule ?? NewPeriodSchedule(),
|
slots ?? new FakeTimetableSlots(), periodSchedule ?? NewPeriodSchedule(),
|
||||||
new AttendanceBalanceService(), new SchoolYearService(), dashboardSettings ?? NewDashboardSettings(),
|
new AttendanceBalanceService(), new SchoolYearService(), dashboardSettings ?? NewDashboardSettings(),
|
||||||
schoolHolidays ?? new FakeSchoolHolidays(), new PublicHolidayService(), NewCalendarSettings(),
|
schoolHolidays ?? new FakeSchoolHolidays(), new PublicHolidayService(), NewCalendarSettings(),
|
||||||
@@ -805,10 +813,365 @@ public sealed class DashboardViewModelTests
|
|||||||
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||||
Assert.Equal(student.FullName, item.Title);
|
Assert.Equal(student.FullName, item.Title);
|
||||||
Assert.Equal("30 %", item.TrailingText);
|
Assert.Equal("30 %", item.TrailingText);
|
||||||
Assert.True(item.IsAttendanceWarning);
|
Assert.True(item.IsCrossClassWarning);
|
||||||
Assert.Equal(AttentionKind.Attendance, vm.Attention.First().Kind);
|
Assert.Equal(AttentionKind.Attendance, vm.Attention.First().Kind);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Fehlzeiten-Warnungen landen seit der Verknüpfung mit dem schülerbezogenen "Vorgänge"-Tab auf
|
||||||
|
/// OnNavigateToStudentCase (mit dem passenden Tag "Absentismus") statt auf OnNavigateToStudent.
|
||||||
|
[Fact]
|
||||||
|
public void AttendanceWarnings_NavigiertUeberOnNavigateToStudentCaseMitAbsentismusTag()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
for (var i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||||
|
sessions.Save(session);
|
||||||
|
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||||
|
}
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||||
|
|
||||||
|
Guid? navigatedStudentId = null; string? navigatedTag = null; string? navigatedTitle = null;
|
||||||
|
vm.OnNavigateToStudentCase = (id, tag, title) => { navigatedStudentId = id; navigatedTag = tag; navigatedTitle = title; };
|
||||||
|
vm.OnNavigateToStudent = _ => throw new InvalidOperationException("sollte nicht mehr aufgerufen werden");
|
||||||
|
|
||||||
|
Assert.Single(Items(vm, AttentionKind.Attendance)).Navigate!.Invoke();
|
||||||
|
|
||||||
|
Assert.Equal(student.Id, navigatedStudentId);
|
||||||
|
Assert.Equal("Absentismus", navigatedTag);
|
||||||
|
Assert.Equal("Fehlzeiten", navigatedTitle);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingHomeworkWarnings_UnterSchwellenwertKeineWarnung()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
|
||||||
|
// Nur 2 offene Hausaufgaben — Schwelle liegt bei 3.
|
||||||
|
for (var i = 0; i < 2; i++)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||||
|
sessions.Save(session);
|
||||||
|
entries.Add(new ParticipationEntry
|
||||||
|
{ SessionId = session.Id, StudentId = student.Id, Homework = HomeworkStatus.MissingOpen });
|
||||||
|
}
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||||
|
|
||||||
|
Assert.Empty(Items(vm, AttentionKind.MissingHomework));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingHomeworkWarnings_MeldetAbSchwellenwertUndZaehltPartiallyCompletedAlsOffen()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
|
||||||
|
// 3 offene/überfällige Hausaufgaben (davon eine PartiallyCompleted, zählt laut
|
||||||
|
// HomeworkDisplay.CountsAsMissing ebenfalls als offen) — erreicht die Schwelle von 3.
|
||||||
|
var statuses = new[] { HomeworkStatus.MissingOpen, HomeworkStatus.MissingOverdue, HomeworkStatus.PartiallyCompleted };
|
||||||
|
for (var i = 0; i < statuses.Length; i++)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||||
|
sessions.Save(session);
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Homework = statuses[i] });
|
||||||
|
}
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||||
|
|
||||||
|
var item = Assert.Single(Items(vm, AttentionKind.MissingHomework));
|
||||||
|
Assert.Equal(student.FullName, item.Title);
|
||||||
|
Assert.Equal("3 offen", item.TrailingText);
|
||||||
|
|
||||||
|
Guid? navigatedStudentId = null; string? navigatedTag = null;
|
||||||
|
vm.OnNavigateToStudentCase = (id, tag, _) => { navigatedStudentId = id; navigatedTag = tag; };
|
||||||
|
item.Navigate!.Invoke();
|
||||||
|
Assert.Equal(student.Id, navigatedStudentId);
|
||||||
|
Assert.Equal("Hausaufgaben", navigatedTag);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LatenessWarnings_UnterSchwellenwertKeineWarnung()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
|
||||||
|
// Nur 7 Verspätungen — Schwelle liegt bei 8.
|
||||||
|
for (var i = 0; i < 7; i++)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||||
|
sessions.Save(session);
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = AttendanceStatus.Late });
|
||||||
|
}
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||||
|
|
||||||
|
Assert.Empty(Items(vm, AttentionKind.Lateness));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Regressionsschutz: Late/SignificantlyLate zählen bewusst NICHT in die Fehlzeitenquote hinein
|
||||||
|
/// (AttendanceBalanceService behandelt sie als Present) — auch wenn ein Schüler die neue
|
||||||
|
/// Verspätungs-Schwelle reißt, darf die bestehende Fehlzeiten-Warnung dadurch nicht auftauchen.
|
||||||
|
[Fact]
|
||||||
|
public void LatenessWarnings_MeldetAbSchwellenwertUndZaehltNichtAlsFehlzeit()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
|
||||||
|
// 5x Late, 3x SignificantlyLate — zusammen 8, erreicht die Schwelle.
|
||||||
|
for (var i = 0; i < 8; i++)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||||
|
sessions.Save(session);
|
||||||
|
var status = i < 5 ? AttendanceStatus.Late : AttendanceStatus.SignificantlyLate;
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||||
|
}
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||||
|
|
||||||
|
var item = Assert.Single(Items(vm, AttentionKind.Lateness));
|
||||||
|
Assert.Equal(student.FullName, item.Title);
|
||||||
|
Assert.Equal("8× verspätet", item.TrailingText);
|
||||||
|
Assert.Empty(Items(vm, AttentionKind.Attendance));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Entschärfen (Nutzer-Feedback: "erledigt" wirkt grau/hinten, ohne dauerhaft stumm zu bleiben) ──
|
||||||
|
|
||||||
|
private static (Student Handled, Student Active) BuildTwoOverThresholdStudents(
|
||||||
|
LearningGroup group, DateOnly today, FakeSessions sessions, FakeEntries entries)
|
||||||
|
{
|
||||||
|
var handled = new Student { FirstName = "Anna", LastName = "Bearbeitet" };
|
||||||
|
var active = new Student { FirstName = "Ben", LastName = "Unbearbeitet" };
|
||||||
|
foreach (var student in new[] { handled, active })
|
||||||
|
for (var i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||||
|
sessions.Save(session);
|
||||||
|
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||||
|
}
|
||||||
|
return (handled, active);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AttendanceWarnings_MitKuerzlichBearbeitetemVorgang_WandertInZurueckgestelltGruppe()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||||
|
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
vorgaenge.Add(new Vorgang
|
||||||
|
{
|
||||||
|
Title = "Fehlzeiten", StudentIds = [handled.Id], Tags = ["Absentismus"],
|
||||||
|
Status = VorgangStatus.Open, UpdatedAt = DateTime.UtcNow.AddDays(-2),
|
||||||
|
});
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||||
|
vorgaenge: vorgaenge);
|
||||||
|
|
||||||
|
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||||
|
Assert.False(item.IsDefused);
|
||||||
|
Assert.Equal(active.FullName, item.Title);
|
||||||
|
var deferred = Assert.Single(DeferredItems(vm));
|
||||||
|
Assert.True(deferred.IsDefused);
|
||||||
|
Assert.Equal(handled.FullName, deferred.Title);
|
||||||
|
Assert.Equal("Fehlzeiten · Vorgang in Bearbeitung", deferred.Subtitle);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AttendanceWarnings_VorgangAelterAlsFrist_BleibtScharf()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var (handled, _) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||||
|
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
// 20 Tage her — jenseits der 14-Tage-Frist (VorgangDefusalGraceDays).
|
||||||
|
vorgaenge.Add(new Vorgang
|
||||||
|
{
|
||||||
|
Title = "Fehlzeiten", StudentIds = [handled.Id], Tags = ["Absentismus"],
|
||||||
|
Status = VorgangStatus.Open, UpdatedAt = DateTime.UtcNow.AddDays(-20),
|
||||||
|
});
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([handled]), sessions: sessions, entries: entries, vorgaenge: vorgaenge);
|
||||||
|
|
||||||
|
Assert.False(Assert.Single(Items(vm, AttentionKind.Attendance)).IsDefused);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AttendanceWarnings_AktiveZurueckstellungIstEntschaerft_AbgelaufeneNichtMehr()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||||
|
|
||||||
|
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||||
|
snoozes.Save(new DashboardWarningSnooze { StudentId = handled.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
|
||||||
|
snoozes.Save(new DashboardWarningSnooze { StudentId = active.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(-1) });
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||||
|
warningSnoozes: snoozes);
|
||||||
|
|
||||||
|
Assert.Equal(active.FullName, Assert.Single(Items(vm, AttentionKind.Attendance)).Title);
|
||||||
|
var deferred = Assert.Single(DeferredItems(vm));
|
||||||
|
Assert.Equal(handled.FullName, deferred.Title);
|
||||||
|
Assert.Equal($"Fehlzeiten · zurückgestellt bis {today.AddDays(7):dd.MM.}", deferred.Subtitle);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ZurueckgestelltGruppe_StehtEingeklapptAmEndeUndZaehltNichtMit()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||||
|
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||||
|
snoozes.Save(new DashboardWarningSnooze { StudentId = handled.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||||
|
warningSnoozes: snoozes);
|
||||||
|
|
||||||
|
var last = vm.Attention.Last();
|
||||||
|
Assert.True(last.IsDeferred);
|
||||||
|
Assert.Null(last.Kind);
|
||||||
|
Assert.False(last.IsExpanded);
|
||||||
|
Assert.Equal(1, vm.AttentionCount);
|
||||||
|
Assert.True(vm.HasOpenAttention);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ZurueckgestelltGruppe_AufklappzustandUeberlebtNeuaufbauUndFilterBlendetAus()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||||
|
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||||
|
snoozes.Save(new DashboardWarningSnooze { StudentId = handled.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
|
||||||
|
snoozes.Save(new DashboardWarningSnooze { StudentId = active.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||||
|
warningSnoozes: snoozes);
|
||||||
|
|
||||||
|
// Nur noch zurückgestellte Warnungen: kein offener Punkt, Kachel bleibt aber erreichbar.
|
||||||
|
Assert.Equal(0, vm.AttentionCount);
|
||||||
|
Assert.False(vm.HasOpenAttention);
|
||||||
|
Assert.False(vm.AttentionCard.IsEmpty);
|
||||||
|
|
||||||
|
vm.Attention.Single(g => g.IsDeferred).ToggleExpandedCommand.Execute(null);
|
||||||
|
var filter = vm.AttentionFilters.Single(f => f.Kind == AttentionKind.Attendance);
|
||||||
|
filter.IsActive = false;
|
||||||
|
Assert.DoesNotContain(vm.Attention, g => g.IsDeferred);
|
||||||
|
filter.IsActive = true;
|
||||||
|
|
||||||
|
Assert.True(vm.Attention.Single(g => g.IsDeferred).IsExpanded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SnoozeAction_FragtNachUndEntschaerftDieWarnungSofort()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
for (var i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||||
|
sessions.Save(session);
|
||||||
|
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||||
|
}
|
||||||
|
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([student]), sessions: sessions, entries: entries, warningSnoozes: snoozes);
|
||||||
|
|
||||||
|
string? shownMessage = null;
|
||||||
|
vm.OnPickSnoozeDuration = message => { shownMessage = message; return Task.FromResult<int?>(14); };
|
||||||
|
|
||||||
|
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||||
|
Assert.False(item.IsDefused);
|
||||||
|
var snoozeAction = Assert.Single(item.Actions, a => a.Label == "Zurückstellen");
|
||||||
|
await ((IAsyncRelayCommand)snoozeAction.Command).ExecuteAsync(null);
|
||||||
|
|
||||||
|
Assert.Contains(student.FullName, shownMessage);
|
||||||
|
var saved = Assert.Single(snoozes.GetAll());
|
||||||
|
Assert.Equal(student.Id, saved.StudentId);
|
||||||
|
Assert.Equal("Absentismus", saved.WarningTag);
|
||||||
|
Assert.Equal(today.AddDays(14), saved.SnoozedUntil);
|
||||||
|
Assert.Empty(Items(vm, AttentionKind.Attendance));
|
||||||
|
Assert.True(Assert.Single(DeferredItems(vm)).IsDefused);
|
||||||
|
Assert.Equal(0, vm.AttentionCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SnoozeAction_AbbruchSpeichertNichts()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
for (var i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||||
|
sessions.Save(session);
|
||||||
|
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||||
|
}
|
||||||
|
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
students: new FakeStudents([student]), sessions: sessions, entries: entries, warningSnoozes: snoozes);
|
||||||
|
vm.OnPickSnoozeDuration = _ => Task.FromResult<int?>(null);
|
||||||
|
|
||||||
|
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||||
|
var snoozeAction = Assert.Single(item.Actions, a => a.Label == "Zurückstellen");
|
||||||
|
await ((IAsyncRelayCommand)snoozeAction.Command).ExecuteAsync(null);
|
||||||
|
|
||||||
|
Assert.Empty(snoozes.GetAll());
|
||||||
|
Assert.False(Assert.Single(Items(vm, AttentionKind.Attendance)).IsDefused);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task AddTask_SpeichertErgebnisUndAktualisiertOffeneAufgaben()
|
public async Task AddTask_SpeichertErgebnisUndAktualisiertOffeneAufgaben()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -308,4 +308,89 @@ public sealed class DocumentationDialogViewModelTests
|
|||||||
|
|
||||||
Assert.Null(storage.OpenRead(storageId));
|
Assert.Null(storage.OpenRead(storageId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Weitere Beteiligte ("Betrifft außerdem") ─────────────────────────────
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WeitereBeteiligte_NeuerEintrag_UebernimmtAuswahlOhneHauptperson()
|
||||||
|
{
|
||||||
|
var anna = new StudentOption(Guid.NewGuid(), "Anna Beispiel");
|
||||||
|
var ben = new StudentOption(Guid.NewGuid(), "Ben Muster");
|
||||||
|
var cem = new StudentOption(Guid.NewGuid(), "Cem Test");
|
||||||
|
var vm = new DocumentationDialogViewModel(anna.Id, null, new FakeAttachmentStorage(),
|
||||||
|
coStudentOptions: [anna, ben, cem])
|
||||||
|
{
|
||||||
|
Title = "Konflikt", TypeName = "Vorkommnis",
|
||||||
|
};
|
||||||
|
Assert.True(vm.HasCoStudents);
|
||||||
|
Assert.True(vm.CoStudents.Single(c => c.Id == anna.Id).IsPrimary);
|
||||||
|
foreach (var c in vm.CoStudents) c.IsSelected = true;
|
||||||
|
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(anna.Id, vm.Result!.StudentId);
|
||||||
|
Assert.Equal([ben.Id, cem.Id], vm.Result.AdditionalStudentIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WeitereBeteiligte_NurHauptpersonAlsKandidat_BlendetAuswahlAus()
|
||||||
|
{
|
||||||
|
var anna = new StudentOption(Guid.NewGuid(), "Anna Beispiel");
|
||||||
|
var vm = new DocumentationDialogViewModel(anna.Id, null, new FakeAttachmentStorage(), coStudentOptions: [anna]);
|
||||||
|
|
||||||
|
Assert.False(vm.HasCoStudents);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WeitereBeteiligte_WechselDerHauptperson_VerschiebtAusblendung()
|
||||||
|
{
|
||||||
|
var anna = new StudentOption(Guid.NewGuid(), "Anna Beispiel");
|
||||||
|
var ben = new StudentOption(Guid.NewGuid(), "Ben Muster");
|
||||||
|
var vm = new DocumentationDialogViewModel(anna.Id, null, new FakeAttachmentStorage(), [anna, ben],
|
||||||
|
coStudentOptions: [anna, ben])
|
||||||
|
{
|
||||||
|
Title = "Konflikt", TypeName = "Vorkommnis",
|
||||||
|
};
|
||||||
|
vm.CoStudents.Single(c => c.Id == anna.Id).IsSelected = true;
|
||||||
|
|
||||||
|
vm.SelectedStudent = ben;
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.True(vm.CoStudents.Single(c => c.Id == ben.Id).IsPrimary);
|
||||||
|
Assert.Equal(ben.Id, vm.Result!.StudentId);
|
||||||
|
Assert.Equal([anna.Id], vm.Result.AdditionalStudentIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WeitereBeteiligte_BearbeitenOhneKandidaten_BehaeltBestehendeBei()
|
||||||
|
{
|
||||||
|
Guid anna = Guid.NewGuid(), ben = Guid.NewGuid();
|
||||||
|
var existing = new Documentation { StudentId = anna, AdditionalStudentIds = [ben], Title = "Konflikt" };
|
||||||
|
var vm = new DocumentationDialogViewModel(ben, existing, new FakeAttachmentStorage());
|
||||||
|
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(anna, vm.Result!.StudentId);
|
||||||
|
Assert.Equal([ben], vm.Result.AdditionalStudentIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WeitereBeteiligte_Bearbeiten_AbwahlEntferntNurAngeboteneKandidaten()
|
||||||
|
{
|
||||||
|
var anna = new StudentOption(Guid.NewGuid(), "Anna Beispiel");
|
||||||
|
var ben = new StudentOption(Guid.NewGuid(), "Ben Muster");
|
||||||
|
var outsider = Guid.NewGuid();
|
||||||
|
var existing = new Documentation
|
||||||
|
{
|
||||||
|
StudentId = anna.Id, AdditionalStudentIds = [ben.Id, outsider], Title = "Konflikt",
|
||||||
|
};
|
||||||
|
var vm = new DocumentationDialogViewModel(anna.Id, existing, new FakeAttachmentStorage(),
|
||||||
|
coStudentOptions: [anna, ben]);
|
||||||
|
Assert.True(vm.CoStudents.Single(c => c.Id == ben.Id).IsSelected);
|
||||||
|
|
||||||
|
vm.CoStudents.Single(c => c.Id == ben.Id).IsSelected = false;
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal([outsider], vm.Result!.AdditionalStudentIds);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class ExamCoverSheetTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _directory = Path.Combine(Path.GetTempPath(), $"lehrerapp-cover-tests-{Guid.NewGuid():N}");
|
||||||
|
private readonly LearningGroup _group = new() { Name = "9 Ch G", SchoolYear = "2025/26", GradeLevel = 9 };
|
||||||
|
private readonly Student _anna = new() { FirstName = "Anna", LastName = "Adler" };
|
||||||
|
private readonly Student _ben = new() { FirstName = "Ben", LastName = "Bauer" };
|
||||||
|
private readonly Exam _exam;
|
||||||
|
private readonly FakeResults _results = new();
|
||||||
|
|
||||||
|
private const string Layout = """
|
||||||
|
PAGE 210 297 mm
|
||||||
|
#pragma format-version 3
|
||||||
|
#pragma page-template first
|
||||||
|
TEXT 20 20 $Student.Name size=12
|
||||||
|
#pragma flow-slot body x=20 y=40 w=170 h=230
|
||||||
|
#pragma end-page-template
|
||||||
|
#pragma content-flow body
|
||||||
|
TEXT $Exam.Title size=14
|
||||||
|
FLOWDRAWBOX $Exam.PointsTable w=170 h=120 fit=content gap=10
|
||||||
|
TEXT "Gesamtpunkte: $Result.Points von $Exam.MaxPoints Punkte" size=11 gap=8
|
||||||
|
TEXT "Note: $Result.Grade" size=14 gap=4
|
||||||
|
#pragma end-content-flow
|
||||||
|
""";
|
||||||
|
|
||||||
|
public ExamCoverSheetTests()
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(_directory);
|
||||||
|
_exam = new Exam
|
||||||
|
{
|
||||||
|
GroupId = _group.Id, Title = "Atombau und PSE", Date = new DateOnly(2025, 12, 18), ExamNumber = 1,
|
||||||
|
Tasks =
|
||||||
|
[
|
||||||
|
new() { Nr = 1, MaxPoints = 5 }, new() { Nr = 2, MaxPoints = 12 },
|
||||||
|
new() { Nr = 3, MaxPoints = 3, IsBonus = true },
|
||||||
|
],
|
||||||
|
GradingKey = [new() { Grade = "1", MinPercent = 90 }, new() { Grade = "6", MinPercent = 0 }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PointsTable_BrichtBeiFesterSpaltenbreiteInWeitereBloeckeUm()
|
||||||
|
{
|
||||||
|
var eight = Enumerable.Range(1, 8).Select(n => new ExamCoverTaskColumn(n.ToString(), n, false, null)).ToList();
|
||||||
|
|
||||||
|
var oneBlock = ExamPointsTableDrawingBuilder.Build(eight.Take(6).ToList(), 170);
|
||||||
|
var twoBlocks = ExamPointsTableDrawingBuilder.Build(eight, 170);
|
||||||
|
|
||||||
|
Assert.Equal(6, ExamPointsTableDrawingBuilder.ColumnsPerBlock(170));
|
||||||
|
Assert.True(twoBlocks.ContentHeight > 2 * oneBlock.ContentHeight);
|
||||||
|
// Spalten bleiben gleich breit - der zweite Block verkleinert nichts.
|
||||||
|
Assert.Equal(Widths(oneBlock), Widths(twoBlocks));
|
||||||
|
Assert.All(twoBlocks.Commands.OfType<DrawRectangle>(), r => Assert.True(r.X + r.Width <= 170));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PointsTable_Bonusaufgabe_OhneNummerMitPlusVorDerPunktzahl()
|
||||||
|
{
|
||||||
|
var drawing = ExamPointsTableDrawingBuilder.Build(
|
||||||
|
[
|
||||||
|
new("1", 5, false, 4.5), new("", 3, true, 1),
|
||||||
|
]);
|
||||||
|
|
||||||
|
var texts = drawing.Commands.OfType<DrawStringEx>().Select(x => x.Text).ToList();
|
||||||
|
Assert.Equal(["Aufgabe", "Max. Punktzahl", "Punktzahl", "Nr. 1", "5", "4,5", "Bonus", "+3", "1"], texts);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PointsTable_VorlageInPunkt_SkaliertDenMillimeterEntwurf()
|
||||||
|
{
|
||||||
|
List<ExamCoverTaskColumn> columns = [new("1", 5, false, null)];
|
||||||
|
var scale = 72f / 25.4f;
|
||||||
|
|
||||||
|
var millimeters = ExamPointsTableDrawingBuilder.Build(columns, 170);
|
||||||
|
var points = ExamPointsTableDrawingBuilder.Build(columns, 170 * scale, scale);
|
||||||
|
|
||||||
|
Assert.Equal(millimeters.ContentHeight * scale, points.ContentHeight, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Dialog_ZeigtNurDeckblattVorlagen_AusBeidenBibliotheken()
|
||||||
|
{
|
||||||
|
var letters = Store(); var worksheets = Store();
|
||||||
|
Import(letters, "brief", "Brief", null);
|
||||||
|
Import(letters, "deckblatt-a", "Deckblatt A", TemplateReportTypes.ExamCover);
|
||||||
|
Import(worksheets, "deckblatt-b", "Deckblatt B", TemplateReportTypes.ExamCover);
|
||||||
|
|
||||||
|
var vm = Build([letters, worksheets]);
|
||||||
|
|
||||||
|
Assert.Equal(["Deckblatt A", "Deckblatt B"], vm.Templates.Select(x => x.Name));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Dialog_VorDerKorrektur_BlankoVorausgewaehlt_NachBeginnAusgefuellt()
|
||||||
|
{
|
||||||
|
Assert.False(Build([Store()]).FillResults);
|
||||||
|
|
||||||
|
_results.Add(new ExamResult { ExamId = _exam.Id, StudentId = _anna.Id, Points = [4, 10, 0], TotalPoints = 14 });
|
||||||
|
|
||||||
|
Assert.True(Build([Store()]).FillResults);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Dialog_AbwesenderSchueler_IstStandardmaessigAbgewaehlt()
|
||||||
|
{
|
||||||
|
_results.Add(new ExamResult { ExamId = _exam.Id, StudentId = _ben.Id, Absent = true });
|
||||||
|
|
||||||
|
var vm = Build([Store()]);
|
||||||
|
|
||||||
|
Assert.True(vm.Students.Single(s => s.Model.Id == _anna.Id).IsIncluded);
|
||||||
|
Assert.False(vm.Students.Single(s => s.Model.Id == _ben.Id).IsIncluded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Generate_SchreibtEinSammelPdfMitEinerSeiteJeSchueler()
|
||||||
|
{
|
||||||
|
_results.Add(new ExamResult
|
||||||
|
{ ExamId = _exam.Id, StudentId = _anna.Id, Points = [4.5, 12, 1], TotalPoints = 17.5 });
|
||||||
|
var store = Store();
|
||||||
|
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
|
||||||
|
var vm = Build([store]);
|
||||||
|
var output = Path.Combine(_directory, "deckblaetter.pdf");
|
||||||
|
|
||||||
|
Assert.True(await vm.GenerateAsync(output));
|
||||||
|
|
||||||
|
using var document = UglyToad.PdfPig.PdfDocument.Open(output);
|
||||||
|
Assert.Equal(2, document.NumberOfPages);
|
||||||
|
var anna = Normalize(document.GetPage(1).Text);
|
||||||
|
var ben = Normalize(document.GetPage(2).Text);
|
||||||
|
Assert.Contains(Normalize(_anna.FullName), anna);
|
||||||
|
Assert.Contains(Normalize(_ben.FullName), ben);
|
||||||
|
Assert.Contains("AtombauundPSE", anna);
|
||||||
|
// Bonusaufgabe zählt nicht zur erreichbaren Punktzahl; erreichte Bonuspunkte schon.
|
||||||
|
Assert.Contains("Gesamtpunkte:17,5von17Punkte", anna);
|
||||||
|
Assert.Contains("Note:1", anna);
|
||||||
|
Assert.Contains("+3", anna);
|
||||||
|
// Ben ist noch nicht korrigiert: Linien zum Ausfüllen statt Punkten und Note.
|
||||||
|
Assert.Contains($"Gesamtpunkte:{ExamCoverPlaceholderBuilder.BlankPoints}von17Punkte", ben);
|
||||||
|
Assert.Contains("1 davon ohne Punkte und Note", vm.StatusMessage);
|
||||||
|
Assert.False(vm.IsGenerating);
|
||||||
|
Assert.True(vm.CanGenerate);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Generate_OhnePunkteEintragen_BleibtAuchBeiKorrigiertenBlanko()
|
||||||
|
{
|
||||||
|
_results.Add(new ExamResult
|
||||||
|
{ ExamId = _exam.Id, StudentId = _anna.Id, Points = [4.5, 12, 1], TotalPoints = 17.5 });
|
||||||
|
var store = Store();
|
||||||
|
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
|
||||||
|
var vm = Build([store]);
|
||||||
|
vm.FillResults = false;
|
||||||
|
var output = Path.Combine(_directory, "blanko.pdf");
|
||||||
|
|
||||||
|
Assert.True(await vm.GenerateAsync(output));
|
||||||
|
|
||||||
|
using var document = UglyToad.PdfPig.PdfDocument.Open(output);
|
||||||
|
Assert.DoesNotContain("17,5", Normalize(document.GetPage(1).Text));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Generate_ZuVieleAufgabenFuerEineSeite_WarntImStatus()
|
||||||
|
{
|
||||||
|
_exam.Tasks = Enumerable.Range(1, 80).Select(n => new ExamTask { Nr = n, MaxPoints = 1 }).ToList();
|
||||||
|
var store = Store();
|
||||||
|
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
|
||||||
|
var vm = Build([store]);
|
||||||
|
|
||||||
|
Assert.True(await vm.GenerateAsync(Path.Combine(_directory, "lang.pdf")));
|
||||||
|
|
||||||
|
Assert.Contains("passen nicht auf eine Seite", vm.StatusMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(GroupType.Course, Niveau.E, "E-Kurs")]
|
||||||
|
[InlineData(GroupType.Course, Niveau.G, "G-Kurs")]
|
||||||
|
[InlineData(GroupType.Course, Niveau.Foerder, "")]
|
||||||
|
[InlineData(GroupType.Course, null, "")]
|
||||||
|
[InlineData(GroupType.Class, Niveau.G, "")]
|
||||||
|
public void CourseLabel_NurImKursMitEOderGNiveau(GroupType type, Niveau? niveau, string expected) =>
|
||||||
|
Assert.Equal(expected, ExamCoverPlaceholderBuilder.CourseLabel(new LearningGroup { Type = type }, niveau));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Platzhalter_KursAusKlausurOderMitgliedschaft_KuerzelAusDemDialog()
|
||||||
|
{
|
||||||
|
_group.Type = GroupType.Course;
|
||||||
|
var store = Store();
|
||||||
|
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
|
||||||
|
var template = store.Load(store.GetTemplates().Single());
|
||||||
|
|
||||||
|
Dictionary<string, PlaceholderValue> Values(Niveau? studentNiveau) => ExamCoverPlaceholderBuilder.Build(
|
||||||
|
_exam, _group, "Chemie", _anna, null, false, new GradingService(), template, new DateOnly(2026, 1, 1),
|
||||||
|
studentNiveau, " MON HED ");
|
||||||
|
|
||||||
|
Assert.Equal(new TextValue("E-Kurs"), Values(Niveau.E)["Exam.Course"]);
|
||||||
|
Assert.Equal(new TextValue("MON HED"), Values(null)["Teacher.Abbreviation"]);
|
||||||
|
_exam.Niveau = Niveau.G;
|
||||||
|
Assert.Equal(new TextValue("G-Kurs"), Values(Niveau.E)["Exam.Course"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Platzhalter_TitelAusDemDialog_LeerNimmtDenKlausurtitel()
|
||||||
|
{
|
||||||
|
var store = Store();
|
||||||
|
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
|
||||||
|
var template = store.Load(store.GetTemplates().Single());
|
||||||
|
|
||||||
|
Dictionary<string, PlaceholderValue> Values(string? title) => ExamCoverPlaceholderBuilder.Build(
|
||||||
|
_exam, _group, "Chemie", _anna, null, false, new GradingService(), template, new DateOnly(2026, 1, 1),
|
||||||
|
title: title);
|
||||||
|
|
||||||
|
Assert.Equal(new TextValue("Klassenarbeit Nr. 1"), Values(" Klassenarbeit Nr. 1 ")["Exam.Title"]);
|
||||||
|
Assert.Equal(new TextValue("Atombau und PSE"), Values(" ")["Exam.Title"]);
|
||||||
|
Assert.Equal(new TextValue("Atombau und PSE"), Values(null)["Exam.Title"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Dialog_TitelIstMitDemKlausurtitelVorbelegt()
|
||||||
|
{
|
||||||
|
var store = Store();
|
||||||
|
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
|
||||||
|
|
||||||
|
var vm = Build([store]);
|
||||||
|
|
||||||
|
Assert.Equal("Atombau und PSE", vm.CoverTitle);
|
||||||
|
vm.CoverTitle = "Klassenarbeit Nr. 1";
|
||||||
|
Assert.Equal("Atombau und PSE", _exam.Title);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Der Vorlagen-Designer bietet genau diesen Katalog an - liefert die Hauptapp einen Namen
|
||||||
|
// nicht oder mit anderem Typ, scheitert die Vorlage erst beim Drucken.
|
||||||
|
[Fact]
|
||||||
|
public void Platzhalter_DeckenDenKatalogDesDesignersMitGleichenTypenAb()
|
||||||
|
{
|
||||||
|
var store = Store();
|
||||||
|
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
|
||||||
|
var template = store.Load(store.GetTemplates().Single());
|
||||||
|
|
||||||
|
var values = ExamCoverPlaceholderBuilder.Build(_exam, _group, "Chemie", _anna, null, false,
|
||||||
|
new GradingService(), template, new DateOnly(2026, 1, 1));
|
||||||
|
|
||||||
|
Assert.All(ExamCoverPlaceholders.All, known =>
|
||||||
|
{
|
||||||
|
Assert.True(values.ContainsKey(known.Name), $"{known.Name} fehlt");
|
||||||
|
Assert.Equal(known.Type, values[known.Name].Type);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TeacherSettings_SpeichertDasKuerzel()
|
||||||
|
{
|
||||||
|
new TeacherSettingsService(_directory).SaveAbbreviation(" HED ");
|
||||||
|
|
||||||
|
Assert.Equal("HED", new TeacherSettingsService(_directory).LoadAbbreviation());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(RepeatGradeRule.Better, "bessere Note")]
|
||||||
|
[InlineData(RepeatGradeRule.Repeat, "Note der Wiederholungsarbeit")]
|
||||||
|
[InlineData(RepeatGradeRule.Original, "Note der ersten Arbeit")]
|
||||||
|
public void Wiederholungsbaustein_ZeigtDieGespeicherteBewertungsregel(RepeatGradeRule rule, string expected)
|
||||||
|
{
|
||||||
|
var original = new Exam { GroupId = _group.Id, Title = "Erste Arbeit", Date = _exam.Date.AddDays(-14) };
|
||||||
|
_exam.RepeatOfExamId = original.Id; _exam.RepeatGradeRule = rule;
|
||||||
|
var template = new LoadedTemplate(new TemplateManifest(), new LayoutParser().Parse(
|
||||||
|
"PAGE 210 297 mm\nFLOWDRAWBOX 20 20 170 240 $Exam.RepeatInfo fit=content"), new Dictionary<string, byte[]>());
|
||||||
|
var drawing = GradeReportDrawingBuilder.Repeat(_exam, original, new ExamResult { Grade = "4" }, template);
|
||||||
|
var text = string.Join(" ", drawing.Commands.OfType<DrawStringEx>().Select(c => c.Text));
|
||||||
|
Assert.Contains(expected, text);
|
||||||
|
Assert.Contains("Note der ersten Arbeit: 4", text);
|
||||||
|
_exam.IsMakeUp = true;
|
||||||
|
text = string.Join(" ", GradeReportDrawingBuilder.Repeat(_exam, original, null, template).Commands.OfType<DrawStringEx>().Select(c => c.Text));
|
||||||
|
Assert.Contains("Nachschreibarbeit", text);
|
||||||
|
Assert.Contains("ersetzt die versäumte", text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Zwischenstandsbaustein_VerlangtDurchgangUndAlleAusgewaehltenSchueler()
|
||||||
|
{
|
||||||
|
var store = Store();
|
||||||
|
var source = Path.Combine(_directory, "zwischenstand.lavorlage");
|
||||||
|
TemplatePackage.Create(source, new TemplateManifest { Id = "zwischenstand", Name = "Zwischenstand",
|
||||||
|
Metadata = new() { [TemplateMetadataKeys.ReportType] = TemplateReportTypes.ExamCover },
|
||||||
|
Placeholders = [new(ReportTextDrawing.InterimGrades, PlaceholderType.Drawing)] },
|
||||||
|
"PAGE 210 297 mm\nFLOWDRAWBOX 20 20 170 240 $Student.InterimGrades fit=content", new Dictionary<string, byte[]>());
|
||||||
|
store.Import(source);
|
||||||
|
var interims = new FakeInterimGrades();
|
||||||
|
interims.Save(new() { StudentId = _anna.Id, GroupId = _group.Id, Date = _exam.Date, Occasion = "Sprechtag", OverallValue = "2" });
|
||||||
|
var vm = new ExamCoverSheetDialogViewModel(_exam, _group, "Chemie", new FakeStudents([_anna, _ben]),
|
||||||
|
new FakeMemberships([]), _results, new GradingService(), [store], new QuestTemplateRenderer(), interims: interims);
|
||||||
|
var output = Path.Combine(_directory, "zwischenstand.pdf");
|
||||||
|
Assert.True(vm.UsesInterimGrades);
|
||||||
|
Assert.False(await vm.GenerateAsync(output));
|
||||||
|
Assert.Contains("auswählen", vm.StatusMessage);
|
||||||
|
vm.SelectedInterimRun = vm.InterimRuns.Single();
|
||||||
|
Assert.False(await vm.GenerateAsync(output));
|
||||||
|
Assert.Contains(_ben.FullName, vm.StatusMessage);
|
||||||
|
Assert.False(File.Exists(output));
|
||||||
|
vm.Students.Single(s => s.Model.Id == _ben.Id).IsIncluded = false;
|
||||||
|
Assert.True(await vm.GenerateAsync(output));
|
||||||
|
using var document = UglyToad.PdfPig.PdfDocument.Open(output);
|
||||||
|
Assert.Contains("Sprechtag", document.GetPage(1).Text);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Normalize(string text) => text.Replace(" ", "");
|
||||||
|
private static List<float> Widths(DrawingValue drawing) =>
|
||||||
|
drawing.Commands.OfType<DrawRectangle>().Select(r => r.Width).Distinct().Order().ToList();
|
||||||
|
|
||||||
|
private ExamCoverSheetDialogViewModel Build(IReadOnlyList<TemplateStore> stores) =>
|
||||||
|
new(_exam, _group, "Chemie", new FakeStudents([_anna, _ben]), new FakeMemberships([]), _results,
|
||||||
|
new GradingService(), stores, new QuestTemplateRenderer());
|
||||||
|
|
||||||
|
private TemplateStore Store() => new(Path.Combine(_directory, $"store-{Guid.NewGuid():N}"));
|
||||||
|
|
||||||
|
private void Import(TemplateStore store, string id, string name, string? reportType)
|
||||||
|
{
|
||||||
|
var source = Path.Combine(_directory, $"{Guid.NewGuid():N}.lavorlage");
|
||||||
|
var manifest = new TemplateManifest
|
||||||
|
{
|
||||||
|
Id = id, Name = name,
|
||||||
|
Placeholders =
|
||||||
|
[
|
||||||
|
new("Student.Name", PlaceholderType.Text), new("Exam.Title", PlaceholderType.Text),
|
||||||
|
new("Exam.MaxPoints", PlaceholderType.Text), new("Result.Points", PlaceholderType.Text),
|
||||||
|
new("Result.Grade", PlaceholderType.Text),
|
||||||
|
new(ExamPointsTableDrawingBuilder.PlaceholderName, PlaceholderType.Drawing),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
if (reportType is not null) manifest.Metadata[TemplateMetadataKeys.ReportType] = reportType;
|
||||||
|
TemplatePackage.Create(source, manifest, Layout, new Dictionary<string, byte[]>());
|
||||||
|
store.Import(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() { if (Directory.Exists(_directory)) Directory.Delete(_directory, true); }
|
||||||
|
}
|
||||||
@@ -61,4 +61,104 @@ public sealed class ExamDialogViewModelTests
|
|||||||
|
|
||||||
Assert.Equal("", vm.WeekLoadHint);
|
Assert.Equal("", vm.WeekLoadHint);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BonusNachtraeglichMarkiert_BerechnetGespeichertesErgebnisNeu()
|
||||||
|
{
|
||||||
|
var exam = MakeExam(new DateOnly(2026, 5, 12));
|
||||||
|
exam.Tasks = [new ExamTask { Nr = 1, MaxPoints = 10 }, new ExamTask { Nr = 2, MaxPoints = 2 }];
|
||||||
|
exam.GradingKey = GradingService.DefaultKey1To6();
|
||||||
|
var result = new ExamResult { ExamId = exam.Id, StudentId = Guid.NewGuid(),
|
||||||
|
Points = [8, 2], TotalPoints = 10, Grade = "2" };
|
||||||
|
var results = new FakeResults();
|
||||||
|
results.Add(result);
|
||||||
|
var vm = new ExamDialogViewModel(new FakeExams([exam]), new FakeCompetencyDomains(),
|
||||||
|
new FakeGradingKeyTemplates(), new GradingService(), exam.GroupId, null, 9,
|
||||||
|
GradingSystem.Grades1To6, "Chemie", false, exam, null,
|
||||||
|
results: results);
|
||||||
|
vm.Tasks[1].IsBonus = true;
|
||||||
|
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.True(exam.Tasks[1].IsBonus);
|
||||||
|
Assert.Equal(10, result.TotalPoints);
|
||||||
|
Assert.Equal("1", result.Grade);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Förderarbeit ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static (ExamDialogViewModel Vm, Exam Original) BuildFollowUpViewModel(DateOnly originalDate)
|
||||||
|
{
|
||||||
|
var original = new Exam { GroupId = Guid.NewGuid(), Title = "Atombau", Date = originalDate };
|
||||||
|
var vm = new ExamDialogViewModel(new FakeExams([original]), new FakeCompetencyDomains(),
|
||||||
|
new FakeGradingKeyTemplates(), new GradingService(), original.GroupId, null, 9,
|
||||||
|
GradingSystem.Grades1To6, "Chemie", false, null, null);
|
||||||
|
vm.Title = "Atombau (Förder)";
|
||||||
|
vm.Tasks.Add(new ExamTaskEditItem("A1", 10, 1, [], []) { OnChanged = () => { } });
|
||||||
|
vm.Tasks[0].MaxPoints = 10;
|
||||||
|
vm.SelectedOriginalExam = original;
|
||||||
|
return (vm, original);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Foerderarbeit_UebernimmtDatumDerErstenArbeitUndDarfAmSelbenTagLiegen()
|
||||||
|
{
|
||||||
|
var (vm, original) = BuildFollowUpViewModel(new DateOnly(2026, 10, 14));
|
||||||
|
|
||||||
|
vm.FollowUpKindName = "Förderarbeit";
|
||||||
|
|
||||||
|
Assert.Equal("14.10.2026", vm.DateText);
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
Assert.Equal("", vm.RepeatError);
|
||||||
|
Assert.NotNull(vm.Result);
|
||||||
|
Assert.True(vm.Result!.IsSupportWork);
|
||||||
|
Assert.False(vm.Result.IsMakeUp);
|
||||||
|
Assert.Equal(original.Id, vm.Result.RepeatOfExamId);
|
||||||
|
Assert.Equal(original.Date, vm.Result.Date);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Foerderarbeit_VorDerErstenArbeit_WirdAbgelehnt()
|
||||||
|
{
|
||||||
|
var (vm, _) = BuildFollowUpViewModel(new DateOnly(2026, 10, 14));
|
||||||
|
vm.FollowUpKindName = "Förderarbeit";
|
||||||
|
|
||||||
|
vm.DateText = "13.10.2026";
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Contains("Förderarbeit", vm.RepeatError);
|
||||||
|
Assert.Null(vm.Result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Nachschreibarbeit_AmSelbenTag_BleibtAbgelehnt()
|
||||||
|
{
|
||||||
|
var (vm, _) = BuildFollowUpViewModel(new DateOnly(2026, 10, 14));
|
||||||
|
vm.FollowUpKindName = "Nachschreibarbeit";
|
||||||
|
|
||||||
|
vm.DateText = "14.10.2026";
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Contains("Nachschreibarbeit", vm.RepeatError);
|
||||||
|
Assert.Null(vm.Result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Foerderarbeit_WirdBeimBearbeitenWiederhergestelltOhneDatumZuUeberschreiben()
|
||||||
|
{
|
||||||
|
var original = new Exam { GroupId = Guid.NewGuid(), Title = "Atombau", Date = new DateOnly(2026, 10, 14) };
|
||||||
|
var support = new Exam
|
||||||
|
{
|
||||||
|
GroupId = original.GroupId, Title = "Förder", Date = new DateOnly(2026, 10, 16),
|
||||||
|
RepeatOfExamId = original.Id, IsSupportWork = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
var vm = new ExamDialogViewModel(new FakeExams([original, support]), new FakeCompetencyDomains(),
|
||||||
|
new FakeGradingKeyTemplates(), new GradingService(), original.GroupId, null, 9,
|
||||||
|
GradingSystem.Grades1To6, "Chemie", false, support, null);
|
||||||
|
|
||||||
|
Assert.True(vm.IsSupportWork);
|
||||||
|
Assert.Equal("16.10.2026", vm.DateText);
|
||||||
|
Assert.False(vm.ShowRepeatRule);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
using LehrerApp.Core.Models;
|
using LehrerApp.Core.Models;
|
||||||
using LehrerApp.Core.Services;
|
using LehrerApp.Core.Services;
|
||||||
using LehrerApp.Desktop.ViewModels.Groups;
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
@@ -62,4 +63,166 @@ public sealed class ExamGradingDialogViewModelTests
|
|||||||
|
|
||||||
Assert.True(vm.Rows[0].Absent);
|
Assert.True(vm.Rows[0].Absent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static ExamGradingDialogViewModel CreateGrid(int studentCount, params ExamTask[] tasks)
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "Q1 Chemie" };
|
||||||
|
var students = Enumerable.Range(0, studentCount)
|
||||||
|
.Select(i => new Student { FirstName = "S", LastName = $"N{i}" }).ToList();
|
||||||
|
var memberships = new FakeMemberships(
|
||||||
|
students.Select(s => new GroupMembership { GroupId = group.Id, StudentId = s.Id }).ToList());
|
||||||
|
var exam = new Exam
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Title = "Klausur 1", Tasks = [.. tasks],
|
||||||
|
GradingKey = GradingService.DefaultKey1To6(),
|
||||||
|
};
|
||||||
|
return new ExamGradingDialogViewModel(new FakeResults(), new FakeStudents(students), memberships,
|
||||||
|
new GradingService(), exam, group.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ExamTask[] ThreeTasks() =>
|
||||||
|
[
|
||||||
|
new() { Nr = 1, MaxPoints = 5 },
|
||||||
|
new() { Nr = 2, MaxPoints = 5 },
|
||||||
|
new() { Nr = 3, MaxPoints = 5 },
|
||||||
|
];
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Enter_SchülerFürSchüler_LäuftDieZeileEntlangUndDannInDieNächste()
|
||||||
|
{
|
||||||
|
var vm = CreateGrid(2, ThreeTasks());
|
||||||
|
|
||||||
|
Assert.Equal((0, 1), vm.NextCell(0, 0, GradingMove.Next));
|
||||||
|
Assert.Equal((1, 0), vm.NextCell(0, 2, GradingMove.Next));
|
||||||
|
Assert.Null(vm.NextCell(1, 2, GradingMove.Next));
|
||||||
|
Assert.Equal((0, 2), vm.NextCell(1, 0, GradingMove.Previous));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Enter_AufgabeFürAufgabe_LäuftDieSpalteHinunterUndDannZurNächstenAufgabe()
|
||||||
|
{
|
||||||
|
var vm = CreateGrid(2, ThreeTasks());
|
||||||
|
vm.EntryOrderName = vm.EntryOrderOptions[1];
|
||||||
|
|
||||||
|
Assert.Equal((1, 0), vm.NextCell(0, 0, GradingMove.Next));
|
||||||
|
Assert.Equal((0, 1), vm.NextCell(1, 0, GradingMove.Next));
|
||||||
|
Assert.Equal((1, 0), vm.NextCell(0, 1, GradingMove.Previous));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Navigation_ÜberspringtAbwesendeUndAndereFassung()
|
||||||
|
{
|
||||||
|
var vm = CreateGrid(3,
|
||||||
|
new ExamTask { Nr = 1, MaxPoints = 5 },
|
||||||
|
new ExamTask { Nr = 2, MaxPoints = 5, Variant = ExamVariant.B },
|
||||||
|
new ExamTask { Nr = 3, MaxPoints = 5 });
|
||||||
|
vm.Rows[1].Absent = true;
|
||||||
|
|
||||||
|
Assert.Equal((0, 2), vm.NextCell(0, 0, GradingMove.Next));
|
||||||
|
Assert.Equal((0, 2), vm.NextCell(0, 0, GradingMove.Right));
|
||||||
|
Assert.Equal((2, 0), vm.NextCell(0, 0, GradingMove.Down));
|
||||||
|
Assert.Null(vm.NextCell(0, 0, GradingMove.Up));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Spaltenüberschriften_ZählenBonusaufgabenNichtMit()
|
||||||
|
{
|
||||||
|
var vm = CreateGrid(1,
|
||||||
|
new ExamTask { Nr = 1, MaxPoints = 5 },
|
||||||
|
new ExamTask { Nr = 2, MaxPoints = 2, IsBonus = true },
|
||||||
|
new ExamTask { Nr = 3, MaxPoints = 5, Title = "Redox" });
|
||||||
|
|
||||||
|
Assert.Equal(["Aufgabe 1", "★ Bonus", "2. Redox"], vm.TaskHeaders);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RecordingResults : FakeResults, IExamResultRepository
|
||||||
|
{
|
||||||
|
public List<ExamResult> Saved { get; } = [];
|
||||||
|
public new void Save(ExamResult result) => Saved.Add(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (ExamGradingDialogViewModel Vm, RecordingResults Results) CreateRecordingGrid(
|
||||||
|
ExamResult? existing = null)
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "Q1 Chemie" };
|
||||||
|
var student = new Student { FirstName = "Ben", LastName = "Cordes" };
|
||||||
|
var exam = new Exam
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Title = "Klausur 1", Tasks = [.. ThreeTasks()],
|
||||||
|
GradingKey = GradingService.DefaultKey1To6(),
|
||||||
|
};
|
||||||
|
var results = new RecordingResults();
|
||||||
|
if (existing is not null)
|
||||||
|
{
|
||||||
|
existing.ExamId = exam.Id; existing.StudentId = student.Id;
|
||||||
|
results.Add(existing);
|
||||||
|
}
|
||||||
|
var vm = new ExamGradingDialogViewModel(results, new FakeStudents([student]),
|
||||||
|
new FakeMemberships([new GroupMembership { GroupId = group.Id, StudentId = student.Id }]),
|
||||||
|
new GradingService(), exam, group.Id);
|
||||||
|
return (vm, results);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NurAngefahreneZelle_LegtKeinErgebnisMitNullPunktenAn()
|
||||||
|
{
|
||||||
|
var (vm, results) = CreateRecordingGrid();
|
||||||
|
|
||||||
|
// Fokus in die Zelle und wieder heraus ohne Eingabe: die View meldet das als TrySetValue(null).
|
||||||
|
vm.Rows[0].Cells[0].TrySetValue(null);
|
||||||
|
vm.Rows[0].Cells[1].TrySetValue(null);
|
||||||
|
|
||||||
|
Assert.Empty(results.Saved);
|
||||||
|
Assert.Equal("", vm.Rows[0].GradeDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ErsterEingetragenerWert_LegtDasErgebnisAn()
|
||||||
|
{
|
||||||
|
var (vm, results) = CreateRecordingGrid();
|
||||||
|
|
||||||
|
vm.Rows[0].Cells[0].TrySetValue(4);
|
||||||
|
|
||||||
|
var saved = Assert.Single(results.Saved);
|
||||||
|
Assert.Equal([4, 0, 0], saved.Points);
|
||||||
|
Assert.Equal(4, saved.TotalPoints);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UnveraenderterWert_SpeichertNichtErneut()
|
||||||
|
{
|
||||||
|
var (vm, results) = CreateRecordingGrid();
|
||||||
|
vm.Rows[0].Cells[0].TrySetValue(4);
|
||||||
|
|
||||||
|
vm.Rows[0].Cells[0].TrySetValue(4);
|
||||||
|
|
||||||
|
Assert.Single(results.Saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LeereZeileMitBestehendemErgebnis_WirdAlsUnkorrigiertGespeichertNichtAlsNull()
|
||||||
|
{
|
||||||
|
var (vm, results) = CreateRecordingGrid(
|
||||||
|
new ExamResult { Points = [4], TotalPoints = 4, Grade = "4" });
|
||||||
|
|
||||||
|
vm.Rows[0].Cells[0].TrySetValue(null);
|
||||||
|
|
||||||
|
var saved = Assert.Single(results.Saved);
|
||||||
|
Assert.Empty(saved.Points);
|
||||||
|
Assert.Null(saved.Grade);
|
||||||
|
Assert.False(ExamCoverSheetService.IsCorrected(saved));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AbwesendheitOhnePunkte_WirdOhnePunkteUndNoteGespeichert()
|
||||||
|
{
|
||||||
|
var (vm, results) = CreateRecordingGrid();
|
||||||
|
|
||||||
|
vm.Rows[0].Absent = true;
|
||||||
|
|
||||||
|
var saved = Assert.Single(results.Saved);
|
||||||
|
Assert.True(saved.Absent);
|
||||||
|
Assert.Empty(saved.Points);
|
||||||
|
Assert.Null(saved.Grade);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
/// Deckt 1.7.1 (datenschutzkonforme Einzelansicht) ab.
|
||||||
|
public sealed class ExamRevealDialogViewModelTests
|
||||||
|
{
|
||||||
|
private static (ExamRevealDialogViewModel Vm, Student Anna, Student Ben) Build()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "Q1 Chemie" };
|
||||||
|
var anna = new Student { FirstName = "Anna", LastName = "Bauer" };
|
||||||
|
var ben = new Student { FirstName = "Ben", LastName = "Cordes" };
|
||||||
|
var withoutResult = new Student { FirstName = "Cara", LastName = "Diehl" };
|
||||||
|
var exam = new Exam
|
||||||
|
{
|
||||||
|
GroupId = group.Id,
|
||||||
|
Title = "Klausur 1",
|
||||||
|
Tasks =
|
||||||
|
[
|
||||||
|
new ExamTask { Nr = 1, MaxPoints = 10 },
|
||||||
|
new ExamTask { Nr = 2, MaxPoints = 10, Variant = ExamVariant.A },
|
||||||
|
new ExamTask { Nr = 3, MaxPoints = 20, Variant = ExamVariant.B },
|
||||||
|
],
|
||||||
|
GradingKey = GradingService.DefaultKey1To6(),
|
||||||
|
};
|
||||||
|
var results = new FakeResults();
|
||||||
|
// Bewusst in "falscher" Reihenfolge eingefügt — die Liste sortiert nach Nachname.
|
||||||
|
results.Add(new ExamResult { ExamId = exam.Id, StudentId = ben.Id, Absent = true });
|
||||||
|
results.Add(new ExamResult
|
||||||
|
{
|
||||||
|
ExamId = exam.Id, StudentId = anna.Id, Points = [7.5, 9, 0], TotalPoints = 16.5,
|
||||||
|
Grade = "2", Variant = ExamVariant.A,
|
||||||
|
});
|
||||||
|
|
||||||
|
var vm = new ExamRevealDialogViewModel(results, new FakeStudents([ben, withoutResult, anna]),
|
||||||
|
new GradingService(), exam);
|
||||||
|
return (vm, anna, ben);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Start_ZeigtErstenSchülerZugedeckt_UndNurSchülerMitErgebnis()
|
||||||
|
{
|
||||||
|
var (vm, _, _) = Build();
|
||||||
|
|
||||||
|
Assert.Equal(["Bauer, Anna", "Cordes, Ben"], vm.Students.Select(s => s.ListName));
|
||||||
|
Assert.Equal("Anna Bauer", vm.SelectedStudent!.DisplayName);
|
||||||
|
Assert.False(vm.IsRevealed);
|
||||||
|
Assert.Equal("1 / 2", vm.PositionLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Ergebnis_ZeigtNotePunkteUndNurAufgabenDerGeschriebenenFassung()
|
||||||
|
{
|
||||||
|
var (vm, _, _) = Build();
|
||||||
|
var anna = vm.SelectedStudent!;
|
||||||
|
|
||||||
|
Assert.Equal("2", anna.GradeDisplay);
|
||||||
|
Assert.Equal("16,5 von 20 Punkten", anna.PointsDisplay);
|
||||||
|
Assert.Equal(
|
||||||
|
[new ExamRevealTaskRow("Aufgabe 1", "7,5", "10"), new ExamRevealTaskRow("Aufgabe 2", "9", "10")],
|
||||||
|
anna.Tasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Schülerwechsel_DecktWiederZu()
|
||||||
|
{
|
||||||
|
var (vm, _, _) = Build();
|
||||||
|
vm.RevealCommand.Execute(null);
|
||||||
|
Assert.True(vm.IsRevealed);
|
||||||
|
|
||||||
|
vm.NextCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.False(vm.IsRevealed);
|
||||||
|
Assert.Equal("Ben Cordes", vm.SelectedStudent!.DisplayName);
|
||||||
|
Assert.True(vm.SelectedStudent.Absent);
|
||||||
|
Assert.Empty(vm.SelectedStudent.Tasks);
|
||||||
|
Assert.False(vm.NextCommand.CanExecute(null));
|
||||||
|
Assert.True(vm.PreviousCommand.CanExecute(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Zudecken_VerstecktErgebnisWieder()
|
||||||
|
{
|
||||||
|
var (vm, _, _) = Build();
|
||||||
|
vm.RevealCommand.Execute(null);
|
||||||
|
|
||||||
|
vm.HideCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.False(vm.IsRevealed);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public class ExamVariantScoringTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Fassungswechsel_BerechnetPunkteUndNoteNeu()
|
||||||
|
{
|
||||||
|
var tasks = new List<ExamTask>
|
||||||
|
{
|
||||||
|
new() { Nr = 1, MaxPoints = 10 },
|
||||||
|
new() { Nr = 2, MaxPoints = 5, Variant = ExamVariant.A },
|
||||||
|
new() { Nr = 3, MaxPoints = 8, Variant = ExamVariant.B },
|
||||||
|
new() { Nr = 4, MaxPoints = 2, IsBonus = true },
|
||||||
|
};
|
||||||
|
var existing = new ExamResult { Points = [8, 5, 8, 2] };
|
||||||
|
var row = new ExamResultRow(Guid.NewGuid(), "Test", tasks, existing,
|
||||||
|
GradingService.DefaultKey1To6(), 15, new GradingService());
|
||||||
|
|
||||||
|
Assert.Equal(15, row.TotalPoints);
|
||||||
|
Assert.False(row.Cells[2].IsApplicable);
|
||||||
|
|
||||||
|
row.VariantName = "B";
|
||||||
|
|
||||||
|
Assert.Equal(18, row.TotalPoints);
|
||||||
|
Assert.False(row.Cells[1].IsApplicable);
|
||||||
|
Assert.True(row.Cells[2].IsApplicable);
|
||||||
|
Assert.Equal(ExamVariant.B, row.ToModel(Guid.NewGuid()).Variant);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -179,6 +179,22 @@ public class FakeSeatingPlans(List<SeatingPlan>? initial = null) : ISeatingPlanR
|
|||||||
public void Restore(Guid trashId) { }
|
public void Restore(Guid trashId) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class FakeStudentGroupPlans : IStudentGroupPlanRepository
|
||||||
|
{
|
||||||
|
private readonly List<StudentGroupPlan> _plans = [];
|
||||||
|
public StudentGroupPlan? GetById(Guid id) => _plans.FirstOrDefault(p => p.Id == id);
|
||||||
|
public List<StudentGroupPlan> GetByGroup(Guid groupId) =>
|
||||||
|
_plans.Where(p => p.GroupId == groupId).ToList();
|
||||||
|
public List<StudentGroupPlan> GetByStudent(Guid studentId) =>
|
||||||
|
_plans.Where(p => p.Groups.Any(g => g.StudentIds.Contains(studentId))).ToList();
|
||||||
|
public void Save(StudentGroupPlan plan)
|
||||||
|
{
|
||||||
|
_plans.RemoveAll(p => p.Id == plan.Id);
|
||||||
|
_plans.Add(plan);
|
||||||
|
}
|
||||||
|
public void Delete(Guid id) => _plans.RemoveAll(p => p.Id == id);
|
||||||
|
}
|
||||||
|
|
||||||
public class FakeTrash(List<TrashedItem>? initial = null) : ITrashRepository
|
public class FakeTrash(List<TrashedItem>? initial = null) : ITrashRepository
|
||||||
{
|
{
|
||||||
private readonly List<TrashedItem> _all = initial ?? [];
|
private readonly List<TrashedItem> _all = initial ?? [];
|
||||||
@@ -240,6 +256,14 @@ public class FakeAspects : IParticipationAspectRepository
|
|||||||
public void Delete(Guid id) => _all.RemoveAll(a => a.Id == id);
|
public void Delete(Guid id) => _all.RemoveAll(a => a.Id == id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class FakeSections(List<ParticipationSection>? initial = null) : IParticipationSectionRepository
|
||||||
|
{
|
||||||
|
private readonly List<ParticipationSection> _all = initial ?? [];
|
||||||
|
public List<ParticipationSection> GetByGroup(Guid groupId) => _all.Where(s => s.GroupId == groupId).ToList();
|
||||||
|
public void Save(ParticipationSection section) { _all.RemoveAll(s => s.Id == section.Id); _all.Add(section); }
|
||||||
|
public void Delete(Guid id) => _all.RemoveAll(s => s.Id == id);
|
||||||
|
}
|
||||||
|
|
||||||
public class FakeGrades : IGradeRepository
|
public class FakeGrades : IGradeRepository
|
||||||
{
|
{
|
||||||
private readonly List<Grade> _all = [];
|
private readonly List<Grade> _all = [];
|
||||||
@@ -320,15 +344,41 @@ public class FakeDocumentation : IDocumentationRepository
|
|||||||
private readonly List<Documentation> _all = [];
|
private readonly List<Documentation> _all = [];
|
||||||
public void Add(Documentation d) => _all.Add(d);
|
public void Add(Documentation d) => _all.Add(d);
|
||||||
public List<Documentation> GetByStudent(Guid studentId) =>
|
public List<Documentation> GetByStudent(Guid studentId) =>
|
||||||
_all.Where(d => d.StudentId == studentId && !d.IsDeleted).ToList();
|
_all.Where(d => d.Concerns(studentId) && !d.IsDeleted).ToList();
|
||||||
public List<Documentation> GetByStudentAndType(Guid studentId, DocumentationType type) =>
|
public List<Documentation> GetByStudentAndType(Guid studentId, DocumentationType type) =>
|
||||||
_all.Where(d => d.StudentId == studentId && d.Type == type && !d.IsDeleted).ToList();
|
_all.Where(d => d.Concerns(studentId) && d.Type == type && !d.IsDeleted).ToList();
|
||||||
public List<Documentation> GetAll() => _all.Where(d => !d.IsDeleted).ToList();
|
public List<Documentation> GetAll() => _all.Where(d => !d.IsDeleted).ToList();
|
||||||
public void Save(Documentation doc) { _all.RemoveAll(d => d.Id == doc.Id); _all.Add(doc); }
|
public void Save(Documentation doc) { _all.RemoveAll(d => d.Id == doc.Id); _all.Add(doc); }
|
||||||
public void Delete(Guid id) { var d = _all.FirstOrDefault(x => x.Id == id); if (d is not null) d.IsDeleted = true; }
|
public void Delete(Guid id) { var d = _all.FirstOrDefault(x => x.Id == id); if (d is not null) d.IsDeleted = true; }
|
||||||
public void HardDelete(Guid id) => _all.RemoveAll(d => d.Id == id);
|
public void HardDelete(Guid id) => _all.RemoveAll(d => d.Id == id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class FakeVorgangRepository : IVorgangRepository
|
||||||
|
{
|
||||||
|
private readonly List<Vorgang> _all = [];
|
||||||
|
public void Add(Vorgang v) => _all.Add(v);
|
||||||
|
public List<Vorgang> GetAll() => _all.Where(v => !v.IsDeleted).ToList();
|
||||||
|
public List<Vorgang> GetByStudent(Guid studentId) =>
|
||||||
|
_all.Where(v => !v.IsDeleted && v.StudentIds.Contains(studentId)).ToList();
|
||||||
|
public Vorgang? GetById(Guid id) => _all.FirstOrDefault(v => v.Id == id && !v.IsDeleted);
|
||||||
|
public void Save(Vorgang vorgang) { _all.RemoveAll(v => v.Id == vorgang.Id); _all.Add(vorgang); }
|
||||||
|
public void Delete(Guid id) { var v = _all.FirstOrDefault(x => x.Id == id); if (v is not null) v.IsDeleted = true; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class FakeDashboardWarningSnoozeRepository : IDashboardWarningSnoozeRepository
|
||||||
|
{
|
||||||
|
private readonly List<DashboardWarningSnooze> _all = [];
|
||||||
|
public DashboardWarningSnooze? Get(Guid studentId, string warningTag) =>
|
||||||
|
_all.FirstOrDefault(s => s.StudentId == studentId && s.WarningTag == warningTag);
|
||||||
|
public List<DashboardWarningSnooze> GetAll() => _all.ToList();
|
||||||
|
public void Save(DashboardWarningSnooze snooze)
|
||||||
|
{
|
||||||
|
snooze.Id = DashboardWarningSnooze.IdFor(snooze.StudentId, snooze.WarningTag);
|
||||||
|
_all.RemoveAll(s => s.Id == snooze.Id);
|
||||||
|
_all.Add(snooze);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public class FakeAttachmentStorage : IAttachmentStorage
|
public class FakeAttachmentStorage : IAttachmentStorage
|
||||||
{
|
{
|
||||||
private readonly Dictionary<string, byte[]> _blobs = [];
|
private readonly Dictionary<string, byte[]> _blobs = [];
|
||||||
@@ -631,6 +681,17 @@ public class FakeTimeEntries : ITimeEntryRepository
|
|||||||
public void Restore(Guid trashId) { } // siehe FakeSeatingPlans.Restore
|
public void Restore(Guid trashId) { } // siehe FakeSeatingPlans.Restore
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class FakeInterimGrades : IInterimGradeRepository
|
||||||
|
{
|
||||||
|
private readonly List<InterimGrade> _all = [];
|
||||||
|
public List<InterimGrade> All => _all;
|
||||||
|
public List<InterimGrade> GetByGroup(Guid groupId) => _all.Where(g => g.GroupId == groupId).ToList();
|
||||||
|
public List<InterimGrade> GetByStudentAndGroup(Guid studentId, Guid groupId) =>
|
||||||
|
_all.Where(g => g.StudentId == studentId && g.GroupId == groupId).ToList();
|
||||||
|
public void Save(InterimGrade grade) { _all.RemoveAll(g => g.Id == grade.Id); _all.Add(grade); }
|
||||||
|
public void Delete(Guid id) => _all.RemoveAll(g => g.Id == id);
|
||||||
|
}
|
||||||
|
|
||||||
public class FakeReportGrades : IReportGradeRepository
|
public class FakeReportGrades : IReportGradeRepository
|
||||||
{
|
{
|
||||||
private readonly List<ReportGrade> _all = [];
|
private readonly List<ReportGrade> _all = [];
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ public sealed class GroupDetailViewModelTests
|
|||||||
new FakeDocumentation(), tasks, groups, new AttendanceBalanceService(), new GradingService(), new SchoolYearService()),
|
new FakeDocumentation(), tasks, groups, new AttendanceBalanceService(), new GradingService(), new SchoolYearService()),
|
||||||
new ParticipationTabViewModel(new FakeSessions([]), new FakeEntries(), new FakeAspects(),
|
new ParticipationTabViewModel(new FakeSessions([]), new FakeEntries(), new FakeAspects(),
|
||||||
students, memberships, groups, new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions()),
|
students, memberships, groups, new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions()),
|
||||||
new GradeOverviewTabViewModel(grades, exams, new FakeResults(), students, memberships, new GradingService()),
|
new GradeOverviewTabViewModel(grades, exams, new FakeResults(), students, memberships, new FakeInterimGrades(), new GradingService()),
|
||||||
new PlanningTabViewModel(new FakeUnits(), new FakeLessons(), groups, subjects,
|
new PlanningTabViewModel(new FakeUnits(), new FakeLessons(), groups, subjects,
|
||||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), new FakeSessions([])),
|
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), new FakeSessions([])),
|
||||||
new CompetencyOverviewTabViewModel(new FakeUnits(), exams, new FakeResults(),
|
new CompetencyOverviewTabViewModel(new FakeUnits(), exams, new FakeResults(),
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||||
|
<PackageReference Include="PdfPig" />
|
||||||
<PackageReference Include="xunit" />
|
<PackageReference Include="xunit" />
|
||||||
<PackageReference Include="xunit.runner.visualstudio">
|
<PackageReference Include="xunit.runner.visualstudio">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
|||||||
@@ -8,6 +8,43 @@ namespace LehrerApp.Desktop.Tests;
|
|||||||
|
|
||||||
public sealed class LessonDialogViewModelTests
|
public sealed class LessonDialogViewModelTests
|
||||||
{
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Save_PersistsParentBeforeLesson()
|
||||||
|
{
|
||||||
|
var lessons = new FakeLessons();
|
||||||
|
var unitId = Guid.NewGuid();
|
||||||
|
var vm = new LessonDialogViewModel(lessons, new FakeShorthandCodes([]),
|
||||||
|
new FakeAlternativeLessonPaths([]), new FakeTimetableSlots(), NewPeriodSchedule(),
|
||||||
|
new FakeAttachmentStorage(), unitId, Guid.NewGuid(), "10c", "Chemie", [], [], null);
|
||||||
|
vm.Topic = "Test";
|
||||||
|
vm.DateText = "09.11.2026";
|
||||||
|
var called = false;
|
||||||
|
vm.BeforeSave = () =>
|
||||||
|
{
|
||||||
|
Assert.Empty(lessons.GetByUnit(unitId));
|
||||||
|
called = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.True(called);
|
||||||
|
Assert.Equal(unitId, Assert.Single(lessons.GetByUnit(unitId)).UnitId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Save_InvalidInputDoesNotPersistParent()
|
||||||
|
{
|
||||||
|
var vm = BuildVm(Guid.NewGuid(), Guid.NewGuid());
|
||||||
|
var called = false;
|
||||||
|
vm.BeforeSave = () => called = true;
|
||||||
|
vm.DateText = "invalid";
|
||||||
|
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.False(called);
|
||||||
|
Assert.Null(vm.Result);
|
||||||
|
}
|
||||||
|
|
||||||
private static PeriodScheduleService NewPeriodSchedule()
|
private static PeriodScheduleService NewPeriodSchedule()
|
||||||
{
|
{
|
||||||
var tempPath = System.IO.Path.Combine(
|
var tempPath = System.IO.Path.Combine(
|
||||||
|
|||||||
@@ -31,8 +31,14 @@ public sealed class PersonalDataExportServiceTests
|
|||||||
Assignments = [new SeatAssignment { Row = 1, Column = 2, StudentId = studentId }],
|
Assignments = [new SeatAssignment { Row = 1, Column = 2, StudentId = studentId }],
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
var groupPlans = new FakeStudentGroupPlans();
|
||||||
|
groupPlans.Save(new StudentGroupPlan
|
||||||
|
{
|
||||||
|
GroupId = groupId, Name = "Projektwoche",
|
||||||
|
Groups = [new StudentGroupPlanGroup { StudentIds = [studentId] }],
|
||||||
|
});
|
||||||
var service = new PersonalDataExportService(students, groups, memberships, grades, results, entries,
|
var service = new PersonalDataExportService(students, groups, memberships, grades, results, entries,
|
||||||
documentation, seatingPlans);
|
documentation, seatingPlans, groupPlans);
|
||||||
|
|
||||||
var json = service.ExportAsJson(studentId);
|
var json = service.ExportAsJson(studentId);
|
||||||
|
|
||||||
@@ -41,6 +47,7 @@ public sealed class PersonalDataExportServiceTests
|
|||||||
Assert.Contains("\"Value\": \"2\"", json);
|
Assert.Contains("\"Value\": \"2\"", json);
|
||||||
Assert.Contains("\"Sitzplan\": \"Standard\"", json);
|
Assert.Contains("\"Sitzplan\": \"Standard\"", json);
|
||||||
Assert.Contains("\"Reihe\": 2", json);
|
Assert.Contains("\"Reihe\": 2", json);
|
||||||
|
Assert.Contains("Projektwoche", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -53,4 +60,23 @@ public sealed class PersonalDataExportServiceTests
|
|||||||
|
|
||||||
Assert.Throws<InvalidOperationException>(() => service.ExportAsJson(Guid.NewGuid()));
|
Assert.Throws<InvalidOperationException>(() => service.ExportAsJson(Guid.NewGuid()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ExportAsJson_EnthaeltGespeichertenPlanAuchNachEndeDerMitgliedschaft()
|
||||||
|
{
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var plans = new FakeStudentGroupPlans();
|
||||||
|
plans.Save(new StudentGroupPlan
|
||||||
|
{
|
||||||
|
GroupId = groupId, Name = "Alte Projektgruppe",
|
||||||
|
Groups = [new StudentGroupPlanGroup { StudentIds = [student.Id] }],
|
||||||
|
});
|
||||||
|
var service = new PersonalDataExportService(
|
||||||
|
new FakeStudents([student]), new FakeGroups([]), new FakeMemberships([]),
|
||||||
|
new FakeGrades(), new FakeResults(), new FakeEntries(), new FakeDocumentation(),
|
||||||
|
new FakeSeatingPlans(), plans);
|
||||||
|
|
||||||
|
Assert.Contains("Alte Projektgruppe", service.ExportAsJson(student.Id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class RandomStudentPickerViewModelTests
|
||||||
|
{
|
||||||
|
private static (RandomStudentPickerViewModel Vm, List<Student> Students, LearningGroup Group) Build(int seed = 17)
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "8a" };
|
||||||
|
var students = new List<Student>
|
||||||
|
{
|
||||||
|
new() { FirstName = "Anna", LastName = "Adler" },
|
||||||
|
new() { FirstName = "Ben", LastName = "Bauer" },
|
||||||
|
new() { FirstName = "Cem", LastName = "Can" },
|
||||||
|
};
|
||||||
|
var memberships = students.Select(s => new GroupMembership
|
||||||
|
{
|
||||||
|
GroupId = group.Id,
|
||||||
|
StudentId = s.Id,
|
||||||
|
}).ToList();
|
||||||
|
var vm = new RandomStudentPickerViewModel(
|
||||||
|
new FakeStudents(students), new FakeGroups([group]), new FakeMemberships(memberships),
|
||||||
|
new FakeSessions([]), new FakeEntries(), group.Id, new Random(seed));
|
||||||
|
return (vm, students, group);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Vollrunde_ZiehtAlleEinmal_BevorJemandWiederholtWird()
|
||||||
|
{
|
||||||
|
var (vm, _, _) = Build();
|
||||||
|
var names = new List<string>();
|
||||||
|
|
||||||
|
for (var i = 0; i < 3; i++)
|
||||||
|
{
|
||||||
|
vm.DrawCommand.Execute(null);
|
||||||
|
names.Add(vm.SelectedStudentName);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(3, names.Distinct().Count());
|
||||||
|
Assert.Contains("Alle waren dran", vm.StatusText);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Reset_StartetZiehungOhneAngezeigtenNamenNeu()
|
||||||
|
{
|
||||||
|
var (vm, _, _) = Build();
|
||||||
|
vm.DrawCommand.Execute(null);
|
||||||
|
|
||||||
|
vm.ResetCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.False(vm.HasDrawnStudent);
|
||||||
|
Assert.Equal("Bereit?", vm.SelectedStudentName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NurHeuteAktiveMitglieder_StehenZurAuswahl()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "8a" };
|
||||||
|
var active = new Student { FirstName = "Aktiv", LastName = "A" };
|
||||||
|
var former = new Student { FirstName = "Ehemalig", LastName = "E" };
|
||||||
|
var memberships = new List<GroupMembership>
|
||||||
|
{
|
||||||
|
new() { GroupId = group.Id, StudentId = active.Id },
|
||||||
|
new() { GroupId = group.Id, StudentId = former.Id, LeftAt = DateOnly.FromDateTime(DateTime.Today).AddDays(-1) },
|
||||||
|
};
|
||||||
|
var vm = new RandomStudentPickerViewModel(
|
||||||
|
new FakeStudents([active, former]), new FakeGroups([group]), new FakeMemberships(memberships),
|
||||||
|
new FakeSessions([]), new FakeEntries(), group.Id, new Random(1));
|
||||||
|
|
||||||
|
vm.DrawCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(active.FullName, vm.SelectedStudentName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IntelligenteZiehung_VermeidetDirekteWiederholung()
|
||||||
|
{
|
||||||
|
var (vm, _, _) = Build(2);
|
||||||
|
vm.SelectionModeName = RandomStudentPickerViewModel.IntelligentLabel;
|
||||||
|
vm.DrawCommand.Execute(null);
|
||||||
|
var first = vm.SelectedStudentName;
|
||||||
|
|
||||||
|
vm.DrawCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.NotEqual(first, vm.SelectedStudentName);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,575 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
/// Tests für den Zeugnisnoten-Assistenten: eigenständige Halbjahre (H1 nur als Kontext in H2),
|
||||||
|
/// Endjahresnote aus den beiden Halbjahresnoten, Speichern/Festschreiben über dieselben
|
||||||
|
/// ReportGrade-Datensätze wie der Zeugnisnoten-Dialog sowie die beiden Graph-Modi.
|
||||||
|
public sealed class ReportGradeAssistantViewModelTests
|
||||||
|
{
|
||||||
|
private static readonly Guid GroupId = Guid.NewGuid();
|
||||||
|
private static readonly Student Anna = new() { Id = Guid.NewGuid(), FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
private static readonly Student Ben = new() { Id = Guid.NewGuid(), FirstName = "Ben", LastName = "Muster" };
|
||||||
|
|
||||||
|
private sealed class Fixture
|
||||||
|
{
|
||||||
|
public List<Exam> Exams { get; } = [];
|
||||||
|
public FakeResults Results { get; } = new();
|
||||||
|
public FakeGrades Grades { get; } = new();
|
||||||
|
public FakeReportGrades ReportGrades { get; } = new();
|
||||||
|
public List<ParticipationSession> Sessions { get; } = [];
|
||||||
|
public FakeEntries Entries { get; } = new();
|
||||||
|
public List<ParticipationSection> Sections { get; } = [];
|
||||||
|
public FakeInterimGrades InterimGrades { get; } = new();
|
||||||
|
|
||||||
|
public ReportGradeAssistantViewModel Build(DateOnly today, int gradeLevel = 8, InterimRunOptions? interim = null)
|
||||||
|
{
|
||||||
|
var schemes = new FakeSchemes();
|
||||||
|
schemes.SetForGroup(GroupId, new GradingScheme { ExamsPercent = 50, ParticipationPercent = 40, OtherPercent = 10 });
|
||||||
|
return new ReportGradeAssistantViewModel(
|
||||||
|
Grades, new FakeExams(Exams), Results, new FakeStudents([Anna, Ben]), new FakeMemberships([]),
|
||||||
|
schemes, ReportGrades, new FakeSessions(Sessions), Entries, new FakeAspects(),
|
||||||
|
new FakeSections(Sections), InterimGrades, new AttendanceBalanceService(), new GradingService(),
|
||||||
|
GroupId, GroupType.Class, GradingSystem.Grades1To6, "Testkurs", "2025/26", gradeLevel, today, interim);
|
||||||
|
}
|
||||||
|
|
||||||
|
public InterimRunDialogViewModel BuildRunDialog(DateOnly today, Guid? preselected = null)
|
||||||
|
{
|
||||||
|
var schemes = new FakeSchemes();
|
||||||
|
schemes.SetForGroup(GroupId, new GradingScheme { ExamsPercent = 50, ParticipationPercent = 40, OtherPercent = 10 });
|
||||||
|
return new InterimRunDialogViewModel(
|
||||||
|
Grades, new FakeExams(Exams), Results, new FakeStudents([Anna, Ben]), new FakeMemberships([]),
|
||||||
|
schemes, ReportGrades, new FakeSessions(Sessions), Entries, new FakeAspects(),
|
||||||
|
new FakeSections(Sections), InterimGrades, new GradingService(),
|
||||||
|
GroupId, GroupType.Class, GradingSystem.Grades1To6, "Testkurs", "2025/26", preselected, today);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddSession(DateOnly date, int rating)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { Id = Guid.NewGuid(), GroupId = GroupId, Date = date };
|
||||||
|
Sessions.Add(session);
|
||||||
|
Entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = Anna.Id,
|
||||||
|
Ratings = [new AspectRating { Key = "quality", Value = rating }] });
|
||||||
|
}
|
||||||
|
|
||||||
|
public Exam AddExam(string title, DateOnly date, string annaGrade)
|
||||||
|
{
|
||||||
|
var exam = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Title = title, Date = date };
|
||||||
|
Exams.Add(exam);
|
||||||
|
Results.Add(new ExamResult { ExamId = exam.Id, StudentId = Anna.Id, Grade = annaGrade });
|
||||||
|
return exam;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddParticipation(DateOnly date, string value, string? note = null) =>
|
||||||
|
Grades.Add(new Grade { StudentId = Anna.Id, GroupId = GroupId, Category = GradeCategory.Participation,
|
||||||
|
Date = date, Value = value, Note = note });
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly DateOnly InH1 = new(2025, 11, 10);
|
||||||
|
private static readonly DateOnly InH2 = new(2026, 4, 20);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Vorbelegung_WaehltDasLaufendeHalbjahr()
|
||||||
|
{
|
||||||
|
Assert.Equal(ParticipationPeriod.H1, new Fixture().Build(InH1).SelectedPeriod.Period);
|
||||||
|
Assert.Equal(ParticipationPeriod.H2, new Fixture().Build(InH2).SelectedPeriod.Period);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Halbjahr_BerechnetNoteUndZeigtTeilbereiche()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
|
||||||
|
f.AddParticipation(new DateOnly(2025, 10, 15), "3");
|
||||||
|
|
||||||
|
var vm = f.Build(InH1);
|
||||||
|
|
||||||
|
// (2*50 + 3*40) / 90 = 2,44 -> 2
|
||||||
|
Assert.Equal("2", vm.CalculatedDisplay);
|
||||||
|
Assert.Contains("2,44", vm.CalculationDetail);
|
||||||
|
Assert.Equal(["2,00", "3,00", "–"], vm.Tiles.Select(t => t.Value));
|
||||||
|
Assert.Equal("2", vm.Students[0].GradeDisplay);
|
||||||
|
Assert.Equal(AssistantGradeStatus.Open, vm.Students[0].Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ZweitesHalbjahr_ErstesZaehltNichtWirdAberAlsKontextGezeigt()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "5");
|
||||||
|
f.AddExam("K2", new DateOnly(2026, 3, 1), "2");
|
||||||
|
f.AddParticipation(new DateOnly(2025, 12, 1), "5");
|
||||||
|
|
||||||
|
var vm = f.Build(InH2);
|
||||||
|
|
||||||
|
Assert.Equal("2", vm.CalculatedDisplay);
|
||||||
|
Assert.Equal(2, vm.Works.Count);
|
||||||
|
Assert.True(vm.Works[0].IsContext);
|
||||||
|
Assert.False(vm.Works[1].IsContext);
|
||||||
|
Assert.True(Assert.Single(vm.ParticipationGrades).IsContext);
|
||||||
|
|
||||||
|
vm.ShowPreviousHalf = false;
|
||||||
|
|
||||||
|
Assert.Equal("K2", Assert.Single(vm.Works).Title);
|
||||||
|
Assert.Empty(vm.ParticipationGrades);
|
||||||
|
Assert.Equal("2", vm.CalculatedDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Schuljahr_VerrechnetHalbjahresnotenUndBevorzugtGespeicherteEntscheidung()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
|
||||||
|
f.AddExam("K2", new DateOnly(2026, 3, 1), "4");
|
||||||
|
var vm = f.Build(InH2);
|
||||||
|
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
|
||||||
|
|
||||||
|
// (2 + 4) / 2 = 3
|
||||||
|
Assert.Equal("3", vm.CalculatedDisplay);
|
||||||
|
Assert.Equal(["2", "4"], vm.Tiles.Select(t => t.Value));
|
||||||
|
|
||||||
|
// Pädagogisch übersteuerte Halbjahresnote geht in die Verrechnung ein, nicht die berechnete.
|
||||||
|
f.ReportGrades.Save(new ReportGrade { StudentId = Anna.Id, GroupId = GroupId, Period = "1. Halbjahr",
|
||||||
|
CalculatedValue = "2", OverrideValue = "1", OverrideReason = "starke Entwicklung" });
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.H2);
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
|
||||||
|
|
||||||
|
// (1 + 4) / 2 = 2,5 -> kaufmännisch 3, pädagogisch 2
|
||||||
|
Assert.Equal("3", vm.CalculatedDisplay);
|
||||||
|
Assert.Contains("2,50", vm.CalculationDetail);
|
||||||
|
vm.RoundingRule = RoundingRule.Pedagogical;
|
||||||
|
Assert.Equal("2", vm.CalculatedDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Klasse10_PruefungsnotenZaehlenWieWeitereHalbjahre()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
|
||||||
|
f.AddExam("K2", new DateOnly(2026, 3, 1), "2");
|
||||||
|
var vm = f.Build(InH2, gradeLevel: 10);
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
|
||||||
|
|
||||||
|
Assert.True(vm.CanEnterExamGrades);
|
||||||
|
Assert.Equal("2", vm.CalculatedDisplay);
|
||||||
|
|
||||||
|
// (2 + 2 + 5) / 3 = 3
|
||||||
|
vm.ProjectExamGrade = "5";
|
||||||
|
Assert.Equal("3", vm.CalculatedDisplay);
|
||||||
|
Assert.Equal(3, vm.Tiles.Count);
|
||||||
|
|
||||||
|
// (2 + 2 + 5 + 5) / 4 = 3,5 -> 4
|
||||||
|
vm.OralExamGrade = "5";
|
||||||
|
Assert.Equal("4", vm.CalculatedDisplay);
|
||||||
|
Assert.Contains("4 Teilnoten", vm.CalculationDetail);
|
||||||
|
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
var record = f.ReportGrades.GetByStudentGroupPeriod(Anna.Id, GroupId, "Gesamtes Schuljahr");
|
||||||
|
Assert.Equal("5", record!.ProjectExamGrade);
|
||||||
|
Assert.Equal("5", record.OralExamGrade);
|
||||||
|
Assert.Equal("4", record.CalculatedValue);
|
||||||
|
Assert.Equal("4", vm.Students[0].GradeDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ReportGradeAssistantViewModel Klasse10Schuljahr(Fixture f, string h1, string h2)
|
||||||
|
{
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), h1);
|
||||||
|
f.AddExam("K2", new DateOnly(2026, 3, 1), h2);
|
||||||
|
var vm = f.Build(InH2, gradeLevel: 10);
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
|
||||||
|
return vm;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Klasse10_SchriftlichePruefungGehtMitEinemDrittelEin()
|
||||||
|
{
|
||||||
|
var vm = Klasse10Schuljahr(new Fixture(), "2", "2");
|
||||||
|
|
||||||
|
// § 14 Abs. 3 ObSchVO: (2 * 2 + 5) / 3 = 3,0
|
||||||
|
vm.WrittenExamGrade = "5";
|
||||||
|
|
||||||
|
Assert.Equal("3", vm.CalculatedDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Klasse10_ZusaetzlicheMuendlicheImSchriftlichenFach_EinsZuEinsOhneRundung()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
var vm = Klasse10Schuljahr(f, "4", "4");
|
||||||
|
vm.WrittenExamGrade = "6";
|
||||||
|
|
||||||
|
// (4 + 4 + 6) / 3 = 4,67 -> 5
|
||||||
|
Assert.Equal("5", vm.CalculatedDisplay);
|
||||||
|
|
||||||
|
// § 13 Abs. 2 PrüfV: (6 + 3) / 2 = 4,5 — bleibt ungerundet; (4 + 4 + 4,5) / 3 = 4,17 -> 4
|
||||||
|
vm.AdditionalOralExamGrade = "3";
|
||||||
|
|
||||||
|
Assert.Equal("4", vm.CalculatedDisplay);
|
||||||
|
Assert.Contains("4,17", vm.CalculationDetail);
|
||||||
|
var tile = vm.Tiles.Single(t => t.Label == "Prüfungsleistung");
|
||||||
|
Assert.Equal("4,5", tile.Value);
|
||||||
|
Assert.Contains("zwischen 4 und 5", tile.Hint);
|
||||||
|
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
var record = f.ReportGrades.GetByStudentGroupPeriod(Anna.Id, GroupId, "Gesamtes Schuljahr");
|
||||||
|
Assert.Equal("6", record!.WrittenExamGrade);
|
||||||
|
Assert.Equal("3", record.AdditionalOralExamGrade);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GenauZwischenZweiNoten_WeistAufPaedagogischeEntscheidungHin()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
|
||||||
|
f.AddExam("K2", new DateOnly(2026, 3, 1), "3");
|
||||||
|
var vm = f.Build(InH2);
|
||||||
|
Assert.Empty(vm.BorderlineHint);
|
||||||
|
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
|
||||||
|
|
||||||
|
// (2 + 3) / 2 = 2,5
|
||||||
|
Assert.Contains("zwischen 2 und 3", vm.BorderlineHint);
|
||||||
|
|
||||||
|
vm.ToggleLockCommand.Execute(null);
|
||||||
|
Assert.Empty(vm.BorderlineHint);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Klasse10_NachpruefungOhneAbschlusspruefung_ZweiZuEins()
|
||||||
|
{
|
||||||
|
var vm = Klasse10Schuljahr(new Fixture(), "5", "5");
|
||||||
|
|
||||||
|
// § 13 Abs. 3 PrüfV: (2 * 5 + 3) / 3 = 4,33 -> 4
|
||||||
|
vm.AdditionalOralExamGrade = "3";
|
||||||
|
|
||||||
|
Assert.Equal("4", vm.CalculatedDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Klasse10_NurEinHalbjahr_UnterrichtlicheLeistungZaehltTrotzdemDoppelt()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K2", new DateOnly(2026, 3, 1), "2");
|
||||||
|
var vm = f.Build(InH2, gradeLevel: 10);
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
|
||||||
|
|
||||||
|
// (2 * 2 + 5) / 3 = 3 — nicht (2 + 5) / 2 = 3,5 -> 4
|
||||||
|
vm.OralExamGrade = "5";
|
||||||
|
|
||||||
|
Assert.Equal("3", vm.CalculatedDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Klasse10_WiderspruechlichePruefungen_WerdenAbgelehnt()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
var vm = Klasse10Schuljahr(f, "3", "3");
|
||||||
|
|
||||||
|
vm.WrittenExamGrade = "3";
|
||||||
|
vm.OralExamGrade = "2";
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
Assert.NotEmpty(vm.OralExamGradeError);
|
||||||
|
|
||||||
|
vm.WrittenExamGrade = "";
|
||||||
|
vm.AdditionalOralExamGrade = "4";
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
Assert.NotEmpty(vm.AdditionalOralExamGradeError);
|
||||||
|
Assert.Equal(0, f.ReportGrades.SavedCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Klasse10_UngueltigePruefungsnote_WirdNichtGespeichert()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
|
||||||
|
var vm = f.Build(InH2, gradeLevel: 10);
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
|
||||||
|
|
||||||
|
vm.ProjectExamGrade = "gut";
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.NotEmpty(vm.ProjectExamGradeError);
|
||||||
|
Assert.Equal(0, f.ReportGrades.SavedCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PruefungsnotenNurInKlasse10UndNurFuerDasSchuljahr()
|
||||||
|
{
|
||||||
|
var klasse8 = new Fixture().Build(InH2);
|
||||||
|
klasse8.SelectedPeriod = klasse8.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
|
||||||
|
Assert.False(klasse8.CanEnterExamGrades);
|
||||||
|
|
||||||
|
Assert.False(new Fixture().Build(InH2, gradeLevel: 10).CanEnterExamGrades);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Speichern_UebersteuernOhneBegruendung_WirdAbgelehnt()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
|
||||||
|
var vm = f.Build(InH1);
|
||||||
|
|
||||||
|
vm.OverrideValue = "2";
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.NotEmpty(vm.OverrideReasonError);
|
||||||
|
Assert.Equal(0, f.ReportGrades.SavedCount);
|
||||||
|
|
||||||
|
vm.OverrideReason = "mündlich deutlich stärker";
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
var record = f.ReportGrades.GetByStudentGroupPeriod(Anna.Id, GroupId, "1. Halbjahr");
|
||||||
|
Assert.NotNull(record);
|
||||||
|
Assert.Equal("3", record.CalculatedValue);
|
||||||
|
Assert.Equal("2", record.OverrideValue);
|
||||||
|
Assert.Equal("2", vm.Students[0].GradeDisplay);
|
||||||
|
Assert.Equal(AssistantGradeStatus.Saved, vm.Students[0].Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SpeichernUndWeiter_GehtZumNaechstenSchueler()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
|
||||||
|
var vm = f.Build(InH1);
|
||||||
|
|
||||||
|
vm.SaveAndNextCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(Ben.Id, vm.SelectedStudent!.StudentId);
|
||||||
|
Assert.Equal("2 / 2", vm.ProgressText);
|
||||||
|
Assert.False(vm.NextStudentCommand.CanExecute(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Festschreiben_FriertBerechnetenStandEin()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
|
||||||
|
var vm = f.Build(InH1);
|
||||||
|
|
||||||
|
vm.ToggleLockCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.True(vm.IsLocked);
|
||||||
|
Assert.Equal(AssistantGradeStatus.Locked, vm.Students[0].Status);
|
||||||
|
|
||||||
|
// Eine später eingetragene Arbeit ändert den festgeschriebenen Stand nicht mehr.
|
||||||
|
f.AddExam("K2", new DateOnly(2025, 12, 1), "1");
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.H2);
|
||||||
|
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.H1);
|
||||||
|
Assert.Equal("3", vm.CalculatedDisplay);
|
||||||
|
|
||||||
|
vm.ToggleLockCommand.Execute(null);
|
||||||
|
Assert.False(vm.IsLocked);
|
||||||
|
Assert.Equal("2", vm.CalculatedDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Mitarbeitsgraph_AbschnitteBlaetternUndVerlaufAmStueck()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.Sections.Add(new ParticipationSection { GroupId = GroupId, Label = "Abschnitt 1",
|
||||||
|
StartDate = new DateOnly(2025, 8, 20), EndDate = new DateOnly(2025, 9, 30) });
|
||||||
|
f.Sections.Add(new ParticipationSection { GroupId = GroupId, Label = "Abschnitt 2",
|
||||||
|
StartDate = new DateOnly(2025, 10, 1), EndDate = new DateOnly(2025, 10, 31) });
|
||||||
|
f.AddParticipation(new DateOnly(2025, 9, 30), "2", "Abschnitt: Abschnitt 1");
|
||||||
|
foreach (var date in new[] { new DateOnly(2025, 9, 2), new DateOnly(2025, 10, 7), new DateOnly(2025, 11, 4) })
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { Id = Guid.NewGuid(), GroupId = GroupId, Date = date };
|
||||||
|
f.Sessions.Add(session);
|
||||||
|
f.Entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = Anna.Id,
|
||||||
|
Ratings = [new AspectRating { Key = "quality", Value = 1 }] });
|
||||||
|
}
|
||||||
|
|
||||||
|
var vm = f.Build(InH1);
|
||||||
|
|
||||||
|
Assert.True(vm.IsSectionMode);
|
||||||
|
Assert.Equal("1 / 3", vm.SectionPosition);
|
||||||
|
Assert.Contains("Abschnittsnote 2", vm.SectionTitle);
|
||||||
|
Assert.Single(Assert.Single(vm.ChartGroups).Points);
|
||||||
|
Assert.False(vm.PreviousSectionCommand.CanExecute(null));
|
||||||
|
|
||||||
|
vm.NextSectionCommand.Execute(null);
|
||||||
|
Assert.Contains("keine Abschnittsnote", vm.SectionTitle);
|
||||||
|
vm.NextSectionCommand.Execute(null);
|
||||||
|
Assert.Contains("vorläufig", vm.SectionTitle);
|
||||||
|
Assert.True(vm.ChartGroups[0].IsOpen);
|
||||||
|
Assert.False(vm.NextSectionCommand.CanExecute(null));
|
||||||
|
|
||||||
|
vm.IsSectionMode = false;
|
||||||
|
|
||||||
|
Assert.Equal(3, vm.ChartGroups.Count);
|
||||||
|
Assert.Equal(3, vm.ChartGroups.Sum(g => g.Points.Count));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Zwischenstand (2.7.5) ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static InterimRunOptions Sprechtag(params Guid[] students) =>
|
||||||
|
new(new DateOnly(2025, 11, 12), "Sprechtag", students);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Zwischenstand_RechnetNurBisZumStichtagUndMitLaufenderMitarbeit()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
|
||||||
|
f.AddExam("K2", new DateOnly(2025, 12, 1), "6"); // nach dem Stichtag
|
||||||
|
f.AddSession(new DateOnly(2025, 10, 20), -2); // laufender Abschnitt, schwache Mitarbeit
|
||||||
|
|
||||||
|
var vm = f.Build(InH1, interim: Sprechtag(Anna.Id));
|
||||||
|
|
||||||
|
Assert.True(vm.IsInterimMode);
|
||||||
|
Assert.Equal(Anna.Id, Assert.Single(vm.Students).StudentId);
|
||||||
|
Assert.Equal("K1", Assert.Single(vm.Works).Title);
|
||||||
|
Assert.Equal("2", vm.InterimWritten);
|
||||||
|
Assert.NotNull(vm.InterimOral);
|
||||||
|
Assert.Contains("laufender Abschnitt", vm.Tiles.Single(t => t.Label == "Mitarbeit").Hint);
|
||||||
|
// Die schwache laufende Mitarbeit zieht den Gesamtstand unter die reine Klausurnote.
|
||||||
|
Assert.True(int.Parse(vm.InterimOverall!) > 2);
|
||||||
|
Assert.Contains("12.11.2025", vm.CalculationDetail);
|
||||||
|
|
||||||
|
// Die Zeugnisnoten-Berechnung selbst bleibt ohne laufenden Abschnitt.
|
||||||
|
var report = f.Build(InH1);
|
||||||
|
Assert.Equal("–", report.Tiles.Single(t => t.Label == "Mitarbeit").Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Zwischenstand_NotierenSpeichertGetrenntVonDerZeugnisnote()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
|
||||||
|
var vm = f.Build(InH1, interim: Sprechtag(Anna.Id, Ben.Id));
|
||||||
|
|
||||||
|
vm.InterimOverall = "";
|
||||||
|
vm.NoteInterimCommand.Execute(null);
|
||||||
|
Assert.NotEmpty(vm.InterimOverallError);
|
||||||
|
Assert.Empty(f.InterimGrades.All);
|
||||||
|
|
||||||
|
vm.InterimOverall = "3-";
|
||||||
|
vm.InterimNote = "Mitarbeit muss besser werden";
|
||||||
|
vm.NoteInterimAndNextCommand.Execute(null);
|
||||||
|
|
||||||
|
var entry = Assert.Single(f.InterimGrades.All);
|
||||||
|
Assert.Equal(Anna.Id, entry.StudentId);
|
||||||
|
Assert.Equal(new DateOnly(2025, 11, 12), entry.Date);
|
||||||
|
Assert.Equal("Sprechtag", entry.Occasion);
|
||||||
|
Assert.Equal("3", entry.WrittenValue);
|
||||||
|
Assert.Equal("3-", entry.OverallValue);
|
||||||
|
Assert.Equal(0, f.ReportGrades.SavedCount);
|
||||||
|
Assert.Equal(AssistantGradeStatus.Noted, vm.Students[0].Status);
|
||||||
|
Assert.Equal("3-", vm.Students[0].GradeDisplay);
|
||||||
|
Assert.Equal(Ben.Id, vm.SelectedStudent!.StudentId);
|
||||||
|
|
||||||
|
// Erneutes Notieren im selben Durchgang überschreibt statt zu verdoppeln.
|
||||||
|
vm.SelectedStudent = vm.Students[0];
|
||||||
|
Assert.True(vm.HasInterimEntry);
|
||||||
|
Assert.Equal("3-", vm.InterimOverall);
|
||||||
|
vm.InterimOverall = "4";
|
||||||
|
vm.NoteInterimCommand.Execute(null);
|
||||||
|
Assert.Equal("4", Assert.Single(f.InterimGrades.All).OverallValue);
|
||||||
|
|
||||||
|
vm.RemoveInterimCommand.Execute(null);
|
||||||
|
Assert.Empty(f.InterimGrades.All);
|
||||||
|
Assert.Equal(AssistantGradeStatus.Open, vm.Students[0].Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Zwischenstaende_ErscheinenImZeugnisnotenModusAlsListeUndMarker()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
|
||||||
|
f.InterimGrades.Save(new InterimGrade { StudentId = Anna.Id, GroupId = GroupId,
|
||||||
|
Date = new DateOnly(2025, 11, 12), Occasion = "Sprechtag", WrittenValue = "3", OverallValue = "3" });
|
||||||
|
|
||||||
|
var vm = f.Build(new DateOnly(2025, 12, 10));
|
||||||
|
|
||||||
|
var row = Assert.Single(vm.InterimEntries);
|
||||||
|
Assert.Equal("12.11.2025 · Sprechtag", row.Title);
|
||||||
|
Assert.Equal("schriftlich 3", row.Detail);
|
||||||
|
Assert.Contains(vm.ChartGroups.SelectMany(g => g.Points), p => p.ExamLabel == "Zwischenstand: 3");
|
||||||
|
Assert.True(vm.IsReportMode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Startdialog_VorauswahlGefaehrdeteUndBestaetigen()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "5");
|
||||||
|
f.Results.Add(new ExamResult { ExamId = f.Exams[0].Id, StudentId = Ben.Id, Grade = "2" });
|
||||||
|
|
||||||
|
var vm = f.BuildRunDialog(new DateOnly(2025, 11, 12));
|
||||||
|
|
||||||
|
Assert.All(vm.Students, s => Assert.True(s.IsSelected));
|
||||||
|
Assert.Equal(["5", "2"], vm.Students.Select(s => s.ProvisionalDisplay));
|
||||||
|
|
||||||
|
vm.SelectAtRiskCommand.Execute(null);
|
||||||
|
Assert.Equal([Anna.Id], vm.Students.Where(s => s.IsSelected).Select(s => s.StudentId));
|
||||||
|
|
||||||
|
vm.OccasionName = "Blauer Brief";
|
||||||
|
Assert.True(vm.Confirm());
|
||||||
|
Assert.Equal(new DateOnly(2025, 11, 12), vm.Result!.Date);
|
||||||
|
Assert.Equal("Blauer Brief", vm.Result.Occasion);
|
||||||
|
Assert.Equal([Anna.Id], vm.Result.StudentIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Startdialog_EinzelfallUndValidierung()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
var vm = f.BuildRunDialog(new DateOnly(2025, 11, 12), preselected: Ben.Id);
|
||||||
|
|
||||||
|
Assert.Equal([Ben.Id], vm.Students.Where(s => s.IsSelected).Select(s => s.StudentId));
|
||||||
|
|
||||||
|
vm.OccasionName = "Elternanfrage";
|
||||||
|
vm.OccasionDetail = "Frau Muster";
|
||||||
|
Assert.Equal("Elternanfrage: Frau Muster", vm.Occasion);
|
||||||
|
|
||||||
|
vm.SelectNoneCommand.Execute(null);
|
||||||
|
Assert.False(vm.Confirm());
|
||||||
|
Assert.NotEmpty(vm.SelectionError);
|
||||||
|
|
||||||
|
vm.DateText = "12.11.2030";
|
||||||
|
Assert.False(vm.Confirm());
|
||||||
|
Assert.NotEmpty(vm.DateTextError);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Startdialog_BegonnenenDurchgangFortsetzen()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.InterimGrades.Save(new InterimGrade { StudentId = Anna.Id, GroupId = GroupId,
|
||||||
|
Date = new DateOnly(2025, 11, 12), Occasion = "Sprechtag: 1. Elternsprechtag", OverallValue = "3" });
|
||||||
|
|
||||||
|
var vm = f.BuildRunDialog(new DateOnly(2025, 12, 1));
|
||||||
|
vm.SelectedExistingRun = Assert.Single(vm.ExistingRuns);
|
||||||
|
|
||||||
|
Assert.Equal("12.11.2025", vm.DateText);
|
||||||
|
Assert.Equal("Sprechtag: 1. Elternsprechtag", vm.Occasion);
|
||||||
|
Assert.Equal("notiert: 3", vm.Students.Single(s => s.StudentId == Anna.Id).NotedDisplay);
|
||||||
|
Assert.Equal("", vm.Students.Single(s => s.StudentId == Ben.Id).NotedDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Notenuebersicht_ZeigtZwischenstaendeAlsEigeneSpalteOhneEinflussAufGesamt()
|
||||||
|
{
|
||||||
|
var f = new Fixture();
|
||||||
|
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
|
||||||
|
f.InterimGrades.Save(new InterimGrade { StudentId = Anna.Id, GroupId = GroupId,
|
||||||
|
Date = new DateOnly(2025, 11, 12), Occasion = "Sprechtag", OverallValue = "5" });
|
||||||
|
|
||||||
|
var vm = new GradeOverviewTabViewModel(f.Grades, new FakeExams(f.Exams), f.Results,
|
||||||
|
new FakeStudents([Anna, Ben]), new FakeMemberships([]), f.InterimGrades, new GradingService());
|
||||||
|
vm.Initialize(GroupId, GradingSystem.Grades1To6, GroupType.Class, "Testkurs", "2025/26");
|
||||||
|
|
||||||
|
var column = vm.Columns.Last();
|
||||||
|
Assert.True(column.IsInterim);
|
||||||
|
Assert.Equal("Zwischenstand 12.11. Sprechtag", column.Header);
|
||||||
|
var anna = vm.Rows.Single(r => r.StudentId == Anna.Id);
|
||||||
|
Assert.Equal("5", anna.Cells.Last());
|
||||||
|
Assert.Equal("2.00", anna.TotalDisplay);
|
||||||
|
Assert.Equal("", vm.Rows.Single(r => r.StudentId == Ben.Id).Cells.Last());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -186,6 +186,33 @@ public class ReportGradeCalculationTests
|
|||||||
Assert.Equal("1", annaNachSperre.FinalDisplay);
|
Assert.Equal("1", annaNachSperre.FinalDisplay);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Schuljahr_WirdAusHalbjahresnotenUndPruefungsnotenVerrechnet()
|
||||||
|
{
|
||||||
|
// H1: eine 1 und eine 2 -> 1,5 -> 2. H2: eine 4 -> 4.
|
||||||
|
var h1a = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Date = new DateOnly(2025, 9, 10), Title = "K1" };
|
||||||
|
var h1b = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Date = new DateOnly(2025, 11, 10), Title = "K2" };
|
||||||
|
var h2 = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Date = new DateOnly(2026, 3, 10), Title = "K3" };
|
||||||
|
var results = new FakeResults();
|
||||||
|
results.Add(new ExamResult { ExamId = h1a.Id, StudentId = Anna.Id, Grade = "1" });
|
||||||
|
results.Add(new ExamResult { ExamId = h1b.Id, StudentId = Anna.Id, Grade = "2" });
|
||||||
|
results.Add(new ExamResult { ExamId = h2.Id, StudentId = Anna.Id, Grade = "4" });
|
||||||
|
var reportGrades = new FakeReportGrades();
|
||||||
|
|
||||||
|
var vm = BuildViewModel(new FakeGrades(), new FakeSchemes(), reportGrades, new FakeExams([h1a, h1b, h2]), results);
|
||||||
|
|
||||||
|
// Aus den Halbjahresnoten: (2 + 4) / 2 = 3 — nicht aus allen Arbeiten ((1+2+4)/3 = 2,33 -> 2).
|
||||||
|
Assert.Equal("3", vm.Rows.Single(r => r.StudentId == Anna.Id).CalculatedValue);
|
||||||
|
|
||||||
|
// Klasse 10: eine im Fach abgelegte Projektprüfung zählt wie ein drittes Halbjahr.
|
||||||
|
reportGrades.Save(new ReportGrade { StudentId = Anna.Id, GroupId = GroupId, Period = "Gesamtes Schuljahr",
|
||||||
|
ProjectExamGrade = "6" });
|
||||||
|
vm.Refresh();
|
||||||
|
|
||||||
|
// (2 + 4 + 6) / 3 = 4
|
||||||
|
Assert.Equal("4", vm.Rows.Single(r => r.StudentId == Anna.Id).CalculatedValue);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ExportCsv_EnthaeltAlleSchuelerDerGruppe()
|
public void ExportCsv_EnthaeltAlleSchuelerDerGruppe()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed partial class SettingsViewModelTests
|
||||||
|
{
|
||||||
|
private const string UsageJson = """
|
||||||
|
{"apiVersion":"1","schema":"lehrerbackend.usage.v1",
|
||||||
|
"period":{"days":28,"from":"2026-09-24T12:00:00","to":"2026-10-22T12:00:00"},
|
||||||
|
"totals":{"calls":3,"chargedUsd":"0.300000","chargedEur":null},
|
||||||
|
"byAction":[
|
||||||
|
{"actionId":"plan","label":"Unterricht planen","operation":null,"calls":2,"chargedUsd":"0.200000","chargedEur":"0.180000"},
|
||||||
|
{"actionId":"worksheet_rewrite_openai","label":"Text überarbeiten","operation":"rewrite","calls":1,"chargedUsd":"0.100000","chargedEur":null}],
|
||||||
|
"entries":[{"at":"2026-10-22T11:00:00","actionId":"plan","label":"Unterricht planen","operation":null,"status":"settled","chargedUsd":"0.100000","chargedEur":"0.090000"}],
|
||||||
|
"entriesTruncated":true,"features":{"spellcheck":true}}
|
||||||
|
""";
|
||||||
|
|
||||||
|
private static AiPlanningService AiWithHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> handler) =>
|
||||||
|
new(new HttpClient(new AccountHandler(handler)) { BaseAddress = new Uri("https://example.invalid/backend/") },
|
||||||
|
new FakeLessons(), new FakeGroups([]), new FakeSubjects([]), new FakeCompetencyDomains(),
|
||||||
|
new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]), TestSupport.BuildAppLogger());
|
||||||
|
|
||||||
|
private static HttpResponseMessage JsonResponse(string json, HttpStatusCode status = HttpStatusCode.OK) =>
|
||||||
|
new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||||
|
|
||||||
|
private sealed class AccountHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> handler) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => handler(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AiAccount_AuthUndVerbrauchWerdenGeladenUndWaehrungenBleibenGetrennt()
|
||||||
|
{
|
||||||
|
var requests = new List<string>();
|
||||||
|
var ai = AiWithHandler(request =>
|
||||||
|
{
|
||||||
|
Assert.Equal("Bearer", request.Headers.Authorization?.Scheme);
|
||||||
|
Assert.Equal("test-token", request.Headers.Authorization?.Parameter);
|
||||||
|
requests.Add(request.RequestUri!.PathAndQuery);
|
||||||
|
return Task.FromResult(JsonResponse(request.RequestUri.AbsolutePath.EndsWith("status.php")
|
||||||
|
? """{"balanceUsd":3.5,"balanceEur":3.1}""" : UsageJson));
|
||||||
|
});
|
||||||
|
var settings = TestSupport.BuildAiSettingsService();
|
||||||
|
var vm = BuildViewModel(aiSettings: settings, aiPlanning: ai);
|
||||||
|
settings.SetCredentialsAndToken("test", "test-token");
|
||||||
|
|
||||||
|
await vm.RefreshAiAccountCommand.ExecuteAsync(null);
|
||||||
|
|
||||||
|
Assert.Equal(["/backend/status.php", "/backend/api/v1/usage.php?days=28"], requests);
|
||||||
|
Assert.Contains("3,50 USD", vm.AiBalanceDisplay);
|
||||||
|
Assert.Contains("3,10 €", vm.AiBalanceDisplay);
|
||||||
|
Assert.True(vm.AiHasUsage);
|
||||||
|
Assert.Equal(2, vm.AiUsageGroups.Count);
|
||||||
|
Assert.Equal(3, vm.AiUsageGroups.Sum(g => g.Calls));
|
||||||
|
Assert.Contains("0,30 USD", vm.AiUsageSummary);
|
||||||
|
Assert.DoesNotContain("€", vm.AiUsageSummary); // Euro-Gegenwert nicht für alle Aufrufe vorhanden
|
||||||
|
Assert.Equal("Unterricht planen", Assert.Single(vm.AiUsageEntries).Label);
|
||||||
|
Assert.Contains("neuesten 1", vm.AiUsageStatus);
|
||||||
|
Assert.Contains("2×", vm.AiFeatures.Single(f => f.ActionId == "plan").Usage);
|
||||||
|
Assert.Equal("Kostenlos", vm.AiFeatures.Single(f => f.ActionId == null).Usage);
|
||||||
|
Assert.False(vm.AiIsRefreshing);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AiAccount_AltesBackend_BehaeltGuthabenUndErklaertFehlendenVerbrauch()
|
||||||
|
{
|
||||||
|
var ai = AiWithHandler(request => Task.FromResult(request.RequestUri!.AbsolutePath.EndsWith("status.php")
|
||||||
|
? JsonResponse("""{"balanceUsd":2}""") : JsonResponse("{}", HttpStatusCode.NotFound)));
|
||||||
|
var settings = TestSupport.BuildAiSettingsService();
|
||||||
|
var vm = BuildViewModel(aiSettings: settings, aiPlanning: ai);
|
||||||
|
settings.SetCredentialsAndToken("test", "token");
|
||||||
|
|
||||||
|
await vm.RefreshAiAccountCommand.ExecuteAsync(null);
|
||||||
|
|
||||||
|
Assert.Equal("Guthaben: 2,00 USD", vm.AiBalanceDisplay);
|
||||||
|
Assert.Contains("noch keine Verbrauchsübersicht", vm.AiUsageStatus);
|
||||||
|
Assert.Empty(vm.AiUsageGroups);
|
||||||
|
Assert.False(vm.AiIsRefreshing);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AiAccount_AbmeldenWaerendLaden_VerhindertRueckkehrDerKontodaten()
|
||||||
|
{
|
||||||
|
var response = new TaskCompletionSource<HttpResponseMessage>();
|
||||||
|
var settings = TestSupport.BuildAiSettingsService();
|
||||||
|
var vm = BuildViewModel(aiSettings: settings, aiPlanning: AiWithHandler(_ => response.Task));
|
||||||
|
settings.SetCredentialsAndToken("test", "token");
|
||||||
|
var refresh = vm.RefreshAiAccountCommand.ExecuteAsync(null);
|
||||||
|
Assert.True(vm.AiIsRefreshing);
|
||||||
|
|
||||||
|
vm.AiLogoutCommand.Execute(null);
|
||||||
|
response.SetResult(JsonResponse("""{"balanceUsd":99}"""));
|
||||||
|
await refresh;
|
||||||
|
|
||||||
|
Assert.False(settings.IsLoggedIn);
|
||||||
|
Assert.False(vm.AiIsLoggedIn);
|
||||||
|
Assert.False(vm.AiIsRefreshing);
|
||||||
|
Assert.Empty(vm.AiBalanceDisplay);
|
||||||
|
Assert.Empty(vm.AiUsageEntries);
|
||||||
|
Assert.Empty(vm.AiUsageGroups);
|
||||||
|
Assert.Contains("Nach der Anmeldung", vm.AiUsageStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("{}")]
|
||||||
|
[InlineData("<html>Fehler</html>")]
|
||||||
|
[InlineData("null")]
|
||||||
|
public async Task AiAccount_UngueltigesGuthaben_LiefertVerstaendlichenFehler(string json)
|
||||||
|
{
|
||||||
|
var ai = AiWithHandler(_ => Task.FromResult(JsonResponse(json)));
|
||||||
|
var error = await Assert.ThrowsAsync<AiBackendException>(() => ai.GetAccountBalanceAsync("token"));
|
||||||
|
Assert.Contains("Guthaben", error.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("0.300000", "null")]
|
||||||
|
[InlineData("lehrerbackend.usage.v1", "unbekannt")]
|
||||||
|
[InlineData("2026-10-22T11:00:00", "ungueltig")]
|
||||||
|
public void AiUsage_UngueltigeAntwortWirdAbgelehnt(string oldValue, string newValue)
|
||||||
|
{
|
||||||
|
Assert.Throws<AiBackendException>(() => AiUsageReport.Parse(UsageJson.Replace(oldValue, newValue)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AiAccount_NetzwerkfehlerUndAbgelaufeneAnmeldungWerdenErklaert()
|
||||||
|
{
|
||||||
|
var unavailable = AiWithHandler(_ => throw new HttpRequestException());
|
||||||
|
Assert.Contains("nicht erreichbar", (await Assert.ThrowsAsync<AiBackendException>(() => unavailable.GetUsageAsync("token"))).Message);
|
||||||
|
var expired = AiWithHandler(_ => Task.FromResult(JsonResponse("{}", HttpStatusCode.Unauthorized)));
|
||||||
|
Assert.Contains("Anmeldung abgelaufen", (await Assert.ThrowsAsync<AiBackendException>(() => expired.GetUsageAsync("token"))).Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ using LehrerApp.Templating;
|
|||||||
|
|
||||||
namespace LehrerApp.Desktop.Tests;
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
public sealed class SettingsViewModelTests
|
public sealed partial class SettingsViewModelTests
|
||||||
{
|
{
|
||||||
private static SettingsViewModel BuildViewModel(FakeSchoolHolidays? holidays = null,
|
private static SettingsViewModel BuildViewModel(FakeSchoolHolidays? holidays = null,
|
||||||
FakeSupervisionDuties? supervisionDuties = null,
|
FakeSupervisionDuties? supervisionDuties = null,
|
||||||
@@ -19,7 +19,7 @@ public sealed class SettingsViewModelTests
|
|||||||
FakeCompetencyCatalogVersions? competencyVersions = null,
|
FakeCompetencyCatalogVersions? competencyVersions = null,
|
||||||
EventQueue? eventQueue = null, SyncKeyStatus? syncKeyStatus = null,
|
EventQueue? eventQueue = null, SyncKeyStatus? syncKeyStatus = null,
|
||||||
SyncKeyRecoveryService? syncKeyRecovery = null, AppearanceSettingsService? appearance = null,
|
SyncKeyRecoveryService? syncKeyRecovery = null, AppearanceSettingsService? appearance = null,
|
||||||
TrashViewModel? trashTab = null)
|
TrashViewModel? trashTab = null, AiSettingsService? aiSettings = null, AiPlanningService? aiPlanning = null)
|
||||||
{
|
{
|
||||||
// Bewusst kein "using": SchoolCalendarSettingsService liest den Pfad erst bei SetState,
|
// Bewusst kein "using": SchoolCalendarSettingsService liest den Pfad erst bei SetState,
|
||||||
// das Verzeichnis muss über die Lebensdauer des ViewModels bestehen bleiben.
|
// das Verzeichnis muss über die Lebensdauer des ViewModels bestehen bleiben.
|
||||||
@@ -37,7 +37,7 @@ public sealed class SettingsViewModelTests
|
|||||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||||
holidays ?? new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath),
|
holidays ?? new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath),
|
||||||
new PeriodScheduleService(tempPath), supervisionDuties ?? new FakeSupervisionDuties(),
|
new PeriodScheduleService(tempPath), supervisionDuties ?? new FakeSupervisionDuties(),
|
||||||
new TemplateStore(tempPath), new WorksheetTemplateStore(new TemplateStore(tempPath, subfolder: "worksheet-template-packages")), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(),
|
new TemplateStore(tempPath), new WorksheetTemplateStore(new TemplateStore(tempPath, subfolder: "worksheet-template-packages")), aiSettings ?? TestSupport.BuildAiSettingsService(), aiPlanning ?? TestSupport.BuildAiPlanningService(),
|
||||||
TestSupport.BuildMcpSettingsService(),
|
TestSupport.BuildMcpSettingsService(),
|
||||||
TestSupport.BuildMcpClientRegistrationService(),
|
TestSupport.BuildMcpClientRegistrationService(),
|
||||||
TestSupport.BuildWebUntisSettingsService(),
|
TestSupport.BuildWebUntisSettingsService(),
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class StudentGroupGeneratorViewModelTests
|
||||||
|
{
|
||||||
|
private static (StudentGroupGeneratorViewModel Vm, List<Student> Students, LearningGroup Group,
|
||||||
|
FakeSessions Sessions, FakeEntries Entries) Build(int studentCount = 10,
|
||||||
|
FakeStudentGroupPlans? savedPlans = null)
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "8a", GradingSystem = GradingSystem.Grades1To6 };
|
||||||
|
var students = Enumerable.Range(1, studentCount).Select(i => new Student
|
||||||
|
{
|
||||||
|
FirstName = $"Kind{i:00}", LastName = "Test",
|
||||||
|
}).ToList();
|
||||||
|
var memberships = students.Select(s => new GroupMembership
|
||||||
|
{
|
||||||
|
GroupId = group.Id, StudentId = s.Id,
|
||||||
|
}).ToList();
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var vm = new StudentGroupGeneratorViewModel(
|
||||||
|
new FakeStudents(students), new FakeGroups([group]), new FakeMemberships(memberships),
|
||||||
|
sessions, entries, new FakeGrades(), group.Id, new Random(7), savedPlans);
|
||||||
|
return (vm, students, group, sessions, entries);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ManuelleUmverteilung_WirdGespeichertUndSpaeterWiederGeladen()
|
||||||
|
{
|
||||||
|
var plans = new FakeStudentGroupPlans();
|
||||||
|
var (vm, students, group, _, _) = Build(6, plans);
|
||||||
|
vm.TargetGroupCount = 2;
|
||||||
|
vm.CountPriority = 100;
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
var source = vm.GeneratedGroups[0];
|
||||||
|
var target = vm.GeneratedGroups[1];
|
||||||
|
var member = source.Members[0];
|
||||||
|
|
||||||
|
Assert.True(vm.MoveStudent(member, target));
|
||||||
|
Assert.False(vm.MoveStudent(member, target));
|
||||||
|
Assert.DoesNotContain(member, source.Members);
|
||||||
|
vm.PlanName = "Projektwoche";
|
||||||
|
vm.SavePlanCommand.Execute(null);
|
||||||
|
|
||||||
|
var saved = Assert.Single(plans.GetByGroup(group.Id));
|
||||||
|
Assert.Equal("Projektwoche", saved.Name);
|
||||||
|
Assert.Contains(member.Id, saved.Groups[1].StudentIds);
|
||||||
|
Assert.False(vm.HasUnsavedChanges);
|
||||||
|
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
vm.SelectedSavedPlan = Assert.Single(vm.SavedPlans);
|
||||||
|
vm.LoadSavedPlanCommand.Execute(null);
|
||||||
|
Assert.Contains(vm.GeneratedGroups[1].Members, m => m.Id == member.Id);
|
||||||
|
Assert.DoesNotContain(vm.GeneratedGroups[0].Members, m => m.Id == member.Id);
|
||||||
|
Assert.False(vm.HasUnsavedChanges);
|
||||||
|
Assert.Equal("Projektwoche", vm.PlanName);
|
||||||
|
|
||||||
|
var reopened = new StudentGroupGeneratorViewModel(
|
||||||
|
new FakeStudents(students), new FakeGroups([group]),
|
||||||
|
new FakeMemberships(students.Select(s => new GroupMembership
|
||||||
|
{
|
||||||
|
GroupId = group.Id, StudentId = s.Id,
|
||||||
|
}).ToList()),
|
||||||
|
new FakeSessions([]), new FakeEntries(), new FakeGrades(), group.Id,
|
||||||
|
savedPlans: plans);
|
||||||
|
reopened.SelectedSavedPlan = Assert.Single(reopened.SavedPlans);
|
||||||
|
reopened.LoadSavedPlanCommand.Execute(null);
|
||||||
|
Assert.Contains(reopened.GeneratedGroups[1].Members, m => m.Id == member.Id);
|
||||||
|
|
||||||
|
reopened.PlanName = "Projektwoche aktualisiert";
|
||||||
|
reopened.SavePlanCommand.Execute(null);
|
||||||
|
Assert.Equal("Projektwoche aktualisiert", Assert.Single(plans.GetByGroup(group.Id)).Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SpeichernUeberschreibtAusgewaehltenPlanErstNachDemLaden()
|
||||||
|
{
|
||||||
|
var plans = new FakeStudentGroupPlans();
|
||||||
|
var (vm, _, group, _, _) = Build(6, plans);
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
vm.PlanName = "Alter Plan";
|
||||||
|
vm.SavePlanCommand.Execute(null);
|
||||||
|
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
vm.SelectedSavedPlan = Assert.Single(vm.SavedPlans);
|
||||||
|
vm.PlanName = "Neuer Plan";
|
||||||
|
vm.SavePlanCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(2, plans.GetByGroup(group.Id).Count);
|
||||||
|
Assert.Contains(plans.GetByGroup(group.Id), p => p.Name == "Alter Plan");
|
||||||
|
Assert.Contains(plans.GetByGroup(group.Id), p => p.Name == "Neuer Plan");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FesteZielgroesse_ErzeugtPassendeAnzahlMitKleinerAusnahme()
|
||||||
|
{
|
||||||
|
var (vm, _, _, _, _) = Build(10);
|
||||||
|
vm.TargetGroupSize = 4;
|
||||||
|
vm.TargetGroupCount = 2;
|
||||||
|
vm.SizePriority = 100;
|
||||||
|
vm.CountPriority = 20;
|
||||||
|
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(3, vm.GeneratedGroups.Count);
|
||||||
|
Assert.Equal(new[] { 3, 3, 4 }, vm.GeneratedGroups.Select(g => g.Members.Count).OrderBy(x => x));
|
||||||
|
Assert.Contains("nicht gleichzeitig", vm.WarningText);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FesteGruppenanzahl_HatVorrangVorZielgroesse()
|
||||||
|
{
|
||||||
|
var (vm, _, _, _, _) = Build(10);
|
||||||
|
vm.TargetGroupSize = 3;
|
||||||
|
vm.TargetGroupCount = 2;
|
||||||
|
vm.SizePriority = 20;
|
||||||
|
vm.CountPriority = 100;
|
||||||
|
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(2, vm.GeneratedGroups.Count);
|
||||||
|
Assert.All(vm.GeneratedGroups, group => Assert.Equal(5, group.Members.Count));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AdHoc_SchliesstHeuteAbwesendeAus()
|
||||||
|
{
|
||||||
|
var (vm, students, group, sessions, entries) = Build(6);
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = DateOnly.FromDateTime(DateTime.Today) };
|
||||||
|
sessions.Save(session);
|
||||||
|
entries.Add(new ParticipationEntry
|
||||||
|
{
|
||||||
|
SessionId = session.Id, StudentId = students[0].Id, Attendance = AttendanceStatus.Excused,
|
||||||
|
});
|
||||||
|
vm.ParticipantModeName = StudentGroupGeneratorViewModel.AdHocModeLabel;
|
||||||
|
vm.TargetGroupCount = 2;
|
||||||
|
vm.CountPriority = 100;
|
||||||
|
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
|
||||||
|
var names = vm.GeneratedGroups.SelectMany(g => g.Members).Select(m => m.Name).ToList();
|
||||||
|
Assert.Equal(5, names.Count);
|
||||||
|
Assert.DoesNotContain(students[0].FullName, names);
|
||||||
|
Assert.Contains("fehlt heute", vm.WarningText);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AdHoc_OhneHeutigeErfassung_WarntUndNutztAlleAktiven()
|
||||||
|
{
|
||||||
|
var (vm, students, _, _, _) = Build(6);
|
||||||
|
vm.ParticipantModeName = StudentGroupGeneratorViewModel.AdHocModeLabel;
|
||||||
|
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(students.Count, vm.GeneratedGroups.SelectMany(g => g.Members).Count());
|
||||||
|
Assert.Contains("keine Anwesenheit", vm.WarningText);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Leistungsverteilung_UnterscheidetHomogeneUndHeterogeneGruppen()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "Kurs", GradingSystem = GradingSystem.Grades1To6 };
|
||||||
|
var students = new[] { "A", "B", "C", "D" }.Select(name => new Student
|
||||||
|
{
|
||||||
|
FirstName = name, LastName = "Test",
|
||||||
|
}).ToList();
|
||||||
|
var memberships = students.Select(s => new GroupMembership { GroupId = group.Id, StudentId = s.Id }).ToList();
|
||||||
|
var grades = new FakeGrades();
|
||||||
|
var values = new[] { "1", "2", "5", "6" };
|
||||||
|
for (var i = 0; i < students.Count; i++)
|
||||||
|
grades.Add(new Grade { GroupId = group.Id, StudentId = students[i].Id, Value = values[i] });
|
||||||
|
var vm = new StudentGroupGeneratorViewModel(
|
||||||
|
new FakeStudents(students), new FakeGroups([group]), new FakeMemberships(memberships),
|
||||||
|
new FakeSessions([]), new FakeEntries(), grades, group.Id, new Random(3))
|
||||||
|
{
|
||||||
|
TargetGroupCount = 2,
|
||||||
|
CountPriority = 100,
|
||||||
|
PerformanceDistribution = -100,
|
||||||
|
};
|
||||||
|
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
var homogeneousFirst = vm.GeneratedGroups[0].Members.Select(m => m.Name).ToHashSet();
|
||||||
|
Assert.Contains(students[0].FullName, homogeneousFirst);
|
||||||
|
Assert.Contains(students[1].FullName, homogeneousFirst);
|
||||||
|
|
||||||
|
vm.PerformanceDistribution = 100;
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
Assert.All(vm.GeneratedGroups, generated =>
|
||||||
|
{
|
||||||
|
var names = generated.Members.Select(m => m.Name).ToHashSet();
|
||||||
|
Assert.True(names.Overlaps([students[0].FullName, students[1].FullName]));
|
||||||
|
Assert.True(names.Overlaps([students[2].FullName, students[3].FullName]));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Paarregeln_ErzwingenZusammenUndTrennenMitHoherPrioritaet()
|
||||||
|
{
|
||||||
|
var (vm, students, _, _, _) = Build(6);
|
||||||
|
vm.TargetGroupCount = 2;
|
||||||
|
vm.CountPriority = 100;
|
||||||
|
vm.PerformanceDistribution = 0;
|
||||||
|
vm.ForcedPairPriority = 100;
|
||||||
|
vm.SelectedPairStudentA = vm.PairCandidates.Single(s => s.Id == students[0].Id);
|
||||||
|
vm.SelectedPairStudentB = vm.PairCandidates.Single(s => s.Id == students[1].Id);
|
||||||
|
vm.AddForcedPairCommand.Execute(null);
|
||||||
|
vm.SelectedPairStudentA = vm.PairCandidates.Single(s => s.Id == students[2].Id);
|
||||||
|
vm.SelectedPairStudentB = vm.PairCandidates.Single(s => s.Id == students[3].Id);
|
||||||
|
vm.AddExcludedPairCommand.Execute(null);
|
||||||
|
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
|
||||||
|
var groupByName = vm.GeneratedGroups.SelectMany((group, index) =>
|
||||||
|
group.Members.Select(member => (member.Name, index)))
|
||||||
|
.ToDictionary(x => x.Name, x => x.index);
|
||||||
|
Assert.Equal(groupByName[students[0].FullName], groupByName[students[1].FullName]);
|
||||||
|
Assert.NotEqual(groupByName[students[2].FullName], groupByName[students[3].FullName]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FoerderschuelerWerdenMoeglichstGleichmaessigVerteilt()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "Kurs" };
|
||||||
|
var students = Enumerable.Range(1, 8).Select(i => new Student
|
||||||
|
{
|
||||||
|
FirstName = $"Kind{i}", LastName = "Test",
|
||||||
|
}).ToList();
|
||||||
|
var memberships = students.Select((student, index) => new GroupMembership
|
||||||
|
{
|
||||||
|
GroupId = group.Id,
|
||||||
|
StudentId = student.Id,
|
||||||
|
Niveau = index < 4 ? Niveau.Foerder : null,
|
||||||
|
}).ToList();
|
||||||
|
var vm = new StudentGroupGeneratorViewModel(
|
||||||
|
new FakeStudents(students), new FakeGroups([group]), new FakeMemberships(memberships),
|
||||||
|
new FakeSessions([]), new FakeEntries(), new FakeGrades(), group.Id, new Random(4))
|
||||||
|
{
|
||||||
|
TargetGroupCount = 2,
|
||||||
|
CountPriority = 100,
|
||||||
|
PerformanceDistribution = -100,
|
||||||
|
DistributeSupportStudents = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
vm.GenerateCommand.Execute(null);
|
||||||
|
|
||||||
|
var supportNames = students.Take(4).Select(s => s.FullName).ToHashSet();
|
||||||
|
Assert.All(vm.GeneratedGroups, generated =>
|
||||||
|
Assert.Equal(2, generated.Members.Count(member => supportNames.Contains(member.Name))));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class StudentReportTests
|
||||||
|
{
|
||||||
|
private readonly Student _student = new() { FirstName = "Erika", LastName = "Beispiel" };
|
||||||
|
private readonly LearningGroup _group = new() { Name = "9 Ch G", SchoolYear = "2026/27" };
|
||||||
|
private readonly DateOnly _date = new(2026, 10, 1);
|
||||||
|
private readonly FakeDocumentation _docs = new();
|
||||||
|
private readonly FakeEntries _entries = new();
|
||||||
|
private readonly FakeAspects _aspects = new();
|
||||||
|
private readonly List<ParticipationSession> _sessions = [];
|
||||||
|
|
||||||
|
private StudentReportService Service() => new(new FakeSessions(_sessions), _entries, _aspects,
|
||||||
|
new FakeExams([]), new FakeResults(), new FakeGrades(), new FakeMemberships([]),
|
||||||
|
new FakeCompetencyDomains(), _docs, new GradingService(), new CompetencyAnalysisService());
|
||||||
|
|
||||||
|
private Dictionary<string, PlaceholderValue> Build(StudentReportOptions? options = null) => Service().Build(
|
||||||
|
_student, _group, StudentReportTemplate.Create(), options ?? new(_date, _date.AddMonths(1), null, IncludeInterim: false));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Dokumentation_IstAufSchuelerGruppeZeitraumUndFreigabeBegrenzt()
|
||||||
|
{
|
||||||
|
Documentation Doc(string title) => new() { StudentId = _student.Id, GroupId = _group.Id, Date = _date, Title = title };
|
||||||
|
_docs.Add(Doc("sichtbar"));
|
||||||
|
var confidential = Doc("vertraulich"); confidential.IsConfidential = true; _docs.Add(confidential);
|
||||||
|
var draft = Doc("Entwurf"); draft.IsDraft = true; _docs.Add(draft);
|
||||||
|
var deleted = Doc("gelöscht"); deleted.IsDeleted = true; _docs.Add(deleted);
|
||||||
|
var otherGroup = Doc("fremdeGruppe"); otherGroup.GroupId = Guid.NewGuid(); _docs.Add(otherGroup);
|
||||||
|
var otherStudent = Doc("fremderSchüler"); otherStudent.StudentId = Guid.NewGuid(); _docs.Add(otherStudent);
|
||||||
|
var outside = Doc("außerhalb"); outside.Date = _date.AddDays(-1); _docs.Add(outside);
|
||||||
|
|
||||||
|
var text = Text((DrawingValue)Build()[StudentReportTemplate.Documentation]);
|
||||||
|
Assert.Contains("sichtbar", text);
|
||||||
|
foreach (var hidden in new[] { "vertraulich", "Entwurf", "gelöscht", "fremdeGruppe", "fremderSchüler", "außerhalb" })
|
||||||
|
Assert.DoesNotContain(hidden, text);
|
||||||
|
var included = Build(new(_date, _date, null, IncludeInterim: false, IncludeConfidential: true));
|
||||||
|
Assert.Contains("[Vertraulich]", Text((DrawingValue)included[StudentReportTemplate.Documentation]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Zwischenstand_MussZumSchuelerZurGruppeUndZumZeitraumPassen()
|
||||||
|
{
|
||||||
|
var interim = new InterimGrade { StudentId = _student.Id, GroupId = _group.Id, Date = _date,
|
||||||
|
Occasion = "Sprechtag", OralValue = "2", WrittenValue = "3", OverallValue = "2-3" };
|
||||||
|
var values = Build(new(_date, _date, interim));
|
||||||
|
Assert.Contains("2-3", Text((DrawingValue)values[ReportTextDrawing.InterimGrades]));
|
||||||
|
interim.StudentId = Guid.NewGuid();
|
||||||
|
Assert.Throws<InvalidDataException>(() => Build(new(_date, _date, interim)));
|
||||||
|
interim.StudentId = _student.Id; interim.GroupId = Guid.NewGuid();
|
||||||
|
Assert.Throws<InvalidDataException>(() => Build(new(_date, _date, interim)));
|
||||||
|
interim.GroupId = _group.Id; interim.Date = _date.AddDays(1);
|
||||||
|
Assert.Throws<InvalidDataException>(() => Build(new(_date, _date, interim)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AbgewaehlteBausteineBleibenLeer()
|
||||||
|
{
|
||||||
|
var values = Build(new(_date, _date, null, false, false, false, false, false));
|
||||||
|
Assert.All(StudentReportTemplate.Drawings, name => Assert.Empty(((DrawingValue)values[name]).Commands));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Hausaufgaben_AltdatenUndFremdeSitzungen()
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = _group.Id, Date = _date };
|
||||||
|
_sessions.Add(session);
|
||||||
|
_entries.Add(new() { StudentId = _student.Id, SessionId = session.Id, HomeworkMissing = true });
|
||||||
|
_entries.Add(new() { StudentId = _student.Id, SessionId = Guid.NewGuid(), Homework = HomeworkStatus.Completed });
|
||||||
|
var text = Text((DrawingValue)Build()[StudentReportTemplate.Homework]);
|
||||||
|
Assert.Contains("Nicht gemacht", text);
|
||||||
|
Assert.DoesNotContain("Hausaufgabe gemacht", text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Standardbericht_RenderbarMitGraphUndMehrseitigerDokumentation()
|
||||||
|
{
|
||||||
|
_aspects.Save(new() { Key = "quality", Label = "Qualität", Weight = 1 });
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = _group.Id, Date = _date.AddDays(i) };
|
||||||
|
_sessions.Add(session);
|
||||||
|
_entries.Add(new() { StudentId = _student.Id, SessionId = session.Id,
|
||||||
|
Ratings = [new() { Key = "quality", Value = i - 2 }], Homework = HomeworkStatus.Completed });
|
||||||
|
}
|
||||||
|
for (var i = 0; i < 55; i++) _docs.Add(new() { StudentId = _student.Id, GroupId = _group.Id,
|
||||||
|
Date = _date, Title = $"Eintrag {i:D2}", Content = "Lange Beobachtung mit einem ausführlichen Text über die regelmäßige Mitarbeit im Unterricht und die Lernfortschritte." });
|
||||||
|
var pdf = new QuestTemplateRenderer().RenderToPdf(StudentReportTemplate.Create(), new ReportProvider(Build()));
|
||||||
|
using var document = UglyToad.PdfPig.PdfDocument.Open(pdf);
|
||||||
|
Assert.True(document.NumberOfPages > 1);
|
||||||
|
Assert.All(document.GetPages(), page => Assert.Contains(_student.FullName.Replace(" ", ""), page.Text.Replace(" ", "")));
|
||||||
|
var text = string.Concat(document.GetPages().Select(p => p.Text)).Replace(" ", "");
|
||||||
|
Assert.Contains(_student.FullName.Replace(" ", ""), text);
|
||||||
|
Assert.Contains("Lerngruppe:9ChG", text);
|
||||||
|
Assert.Contains("GewichteteMitarbeit", text);
|
||||||
|
Assert.Contains("Eintrag54", text);
|
||||||
|
Assert.Contains("Lernfortschritte.", text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Dialog_UngueltigeDatumsangabenErzeugenKeineDatei()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var vm = new StudentReportDialogViewModel(_student,
|
||||||
|
new FakeMemberships([new() { StudentId = _student.Id, GroupId = _group.Id }]),
|
||||||
|
new FakeGroups([_group]), new FakeInterimGrades(), Service(), new QuestTemplateRenderer(),
|
||||||
|
new SchoolYearService(), [new TemplateStore(directory)]);
|
||||||
|
vm.From = "31.02.2026";
|
||||||
|
var output = Path.Combine(directory, "bericht.pdf");
|
||||||
|
Assert.False(await vm.GenerateAsync(output));
|
||||||
|
Assert.False(File.Exists(output));
|
||||||
|
Assert.Contains("TT.MM.JJJJ", vm.StatusMessage);
|
||||||
|
}
|
||||||
|
finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class ReportProvider(IReadOnlyDictionary<string, PlaceholderValue> values) : ITemplateDataProvider
|
||||||
|
{ public IReadOnlyDictionary<string, PlaceholderValue> GetValues() => values; }
|
||||||
|
|
||||||
|
private static string Text(DrawingValue drawing) => string.Join(" ", drawing.Commands.OfType<DrawStringEx>().Select(c => c.Text));
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
/// Tests für den schülerbezogenen "Vorgänge"-Tab im Schülerdetail (StudentVorgaengeViewModel) —
|
||||||
|
/// der universelle, klassenübergreifende Einstiegspunkt für die Dashboard-Warnungen (Fehlzeiten,
|
||||||
|
/// Hausaufgaben-Rückstand, Verspätungen). Anders als ClassTeacherCasesViewModel keine
|
||||||
|
/// Roster-/WebUntis-Abhängigkeit, deshalb reine In-Memory-Fakes ohne Untis-Cache-Setup.
|
||||||
|
public sealed class StudentVorgaengeViewModelTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task BestehenderAkteneintrag_KannNachtraeglichVerknuepftUndWiederGeloestWerden()
|
||||||
|
{
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var doc = new Documentation { StudentId = student.Id, Title = "Bericht" };
|
||||||
|
var documentation = new FakeDocumentation();
|
||||||
|
documentation.Add(doc);
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
var vorgang = new Vorgang { Title = "Vorgang", StudentIds = [student.Id] };
|
||||||
|
vorgaenge.Add(vorgang);
|
||||||
|
var vm = BuildVm(vorgaenge, documentation, new FakeStudents([student]));
|
||||||
|
vm.Load(student.Id);
|
||||||
|
var item = Assert.Single(vm.Cases);
|
||||||
|
item.IsRevealed = true;
|
||||||
|
var available = Assert.Single(item.AvailableDocumentation);
|
||||||
|
var notifications = new List<string?>();
|
||||||
|
item.PropertyChanged += (_, e) => notifications.Add(e.PropertyName);
|
||||||
|
|
||||||
|
// Die View bindet schon vor dem Befuellen der Collections an diese Eigenschaften.
|
||||||
|
item.AvailableDocumentation.Clear();
|
||||||
|
Assert.Contains(nameof(VorgangItem.HasAvailableDocumentation), notifications);
|
||||||
|
Assert.False(item.HasAvailableDocumentation);
|
||||||
|
item.AvailableDocumentation.Add(available);
|
||||||
|
Assert.True(item.HasAvailableDocumentation);
|
||||||
|
|
||||||
|
await item.LinkCommand.ExecuteAsync(available);
|
||||||
|
var linked = Assert.Single(vm.Cases);
|
||||||
|
Assert.True(linked.IsRevealed);
|
||||||
|
Assert.True(linked.HasLinkedDocumentation);
|
||||||
|
Assert.False(linked.HasAvailableDocumentation);
|
||||||
|
Assert.Equal(doc.Id, Assert.Single(linked.LinkedDocumentation).Model.Id);
|
||||||
|
Assert.Contains(doc.Id, vorgaenge.GetById(vorgang.Id)!.DocumentationIds);
|
||||||
|
|
||||||
|
await linked.UnlinkCommand.ExecuteAsync(linked.LinkedDocumentation[0]);
|
||||||
|
var unlinked = Assert.Single(vm.Cases);
|
||||||
|
Assert.False(unlinked.HasLinkedDocumentation);
|
||||||
|
Assert.True(unlinked.HasAvailableDocumentation);
|
||||||
|
Assert.Empty(vorgaenge.GetById(vorgang.Id)!.DocumentationIds);
|
||||||
|
Assert.Equal(doc.Id, Assert.Single(documentation.GetByStudent(student.Id)).Id);
|
||||||
|
}
|
||||||
|
private static StudentVorgaengeViewModel BuildVm(FakeVorgangRepository? vorgaenge = null,
|
||||||
|
FakeDocumentation? documentation = null, FakeStudents? students = null) =>
|
||||||
|
new(vorgaenge ?? new FakeVorgangRepository(), documentation ?? new FakeDocumentation(),
|
||||||
|
students ?? new FakeStudents([]));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Load_ZeigtNurVorgaengeDiesesSchuelers()
|
||||||
|
{
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var other = new Student { FirstName = "Ben", LastName = "Fremd" };
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
vorgaenge.Add(new Vorgang { Title = "Eigener Vorgang", StudentIds = [student.Id] });
|
||||||
|
vorgaenge.Add(new Vorgang { Title = "Fremder Vorgang", StudentIds = [other.Id] });
|
||||||
|
|
||||||
|
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student, other]));
|
||||||
|
vm.Load(student.Id);
|
||||||
|
|
||||||
|
var item = Assert.Single(vm.Cases);
|
||||||
|
Assert.Equal("Eigener Vorgang", item.Model.Title);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Load_OnlyOpenFiltertGeschlosseneVorgaenge()
|
||||||
|
{
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
vorgaenge.Add(new Vorgang { Title = "Offen", StudentIds = [student.Id], Status = VorgangStatus.Open });
|
||||||
|
vorgaenge.Add(new Vorgang { Title = "Geschlossen", StudentIds = [student.Id], Status = VorgangStatus.Closed });
|
||||||
|
|
||||||
|
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
|
||||||
|
vm.Load(student.Id);
|
||||||
|
|
||||||
|
Assert.Equal("Offen", Assert.Single(vm.Cases).Model.Title);
|
||||||
|
|
||||||
|
vm.OnlyOpen = false;
|
||||||
|
Assert.Equal(2, vm.Cases.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleWarningNavigation_RevealtBestehendenOffenenVorgangMitPassendemTag_OhneRueckfrage()
|
||||||
|
{
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
vorgaenge.Add(new Vorgang { Title = "Fehlzeiten", StudentIds = [student.Id], Tags = ["Absentismus"] });
|
||||||
|
|
||||||
|
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
|
||||||
|
vm.Load(student.Id);
|
||||||
|
|
||||||
|
var confirmCalled = false;
|
||||||
|
vm.OnConfirmCreateForWarning = _ => { confirmCalled = true; return Task.FromResult(true); };
|
||||||
|
|
||||||
|
await vm.HandleWarningNavigation("Absentismus", "Fehlzeiten");
|
||||||
|
|
||||||
|
Assert.False(confirmCalled);
|
||||||
|
Assert.True(Assert.Single(vm.Cases).IsRevealed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleWarningNavigation_IgnoriertGeschlosseneVorgaengeMitPassendemTag()
|
||||||
|
{
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
vorgaenge.Add(new Vorgang
|
||||||
|
{ Title = "Alt", StudentIds = [student.Id], Tags = ["Absentismus"], Status = VorgangStatus.Closed });
|
||||||
|
|
||||||
|
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
|
||||||
|
vm.Load(student.Id); // OnlyOpen=true (Default) -> der geschlossene Vorgang ist gar nicht in Cases
|
||||||
|
|
||||||
|
var confirmCalled = false;
|
||||||
|
vm.OnConfirmCreateForWarning = _ => { confirmCalled = true; return Task.FromResult(false); };
|
||||||
|
vm.OnEditVorgang = (_, _) => Task.FromResult<Vorgang?>(null);
|
||||||
|
|
||||||
|
await vm.HandleWarningNavigation("Absentismus", "Fehlzeiten");
|
||||||
|
|
||||||
|
Assert.True(confirmCalled);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleWarningNavigation_KeinPassenderVorgang_FragtNachUndLegtAnBeiZustimmung()
|
||||||
|
{
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
|
||||||
|
vm.Load(student.Id);
|
||||||
|
|
||||||
|
string? confirmedTag = null;
|
||||||
|
vm.OnConfirmCreateForWarning = tag => { confirmedTag = tag; return Task.FromResult(true); };
|
||||||
|
List<StudentOption>? passedOptions = null;
|
||||||
|
Vorgang? passedDraft = null;
|
||||||
|
vm.OnEditVorgang = (options, editing) =>
|
||||||
|
{
|
||||||
|
passedOptions = options;
|
||||||
|
passedDraft = editing;
|
||||||
|
return Task.FromResult(editing);
|
||||||
|
};
|
||||||
|
|
||||||
|
await vm.HandleWarningNavigation("Hausaufgaben", "Hausaufgaben");
|
||||||
|
|
||||||
|
Assert.Equal("Hausaufgaben", confirmedTag);
|
||||||
|
Assert.Equal(student.Id, Assert.Single(passedOptions!).Id);
|
||||||
|
Assert.Equal("Hausaufgaben", passedDraft!.Title);
|
||||||
|
Assert.Contains("Hausaufgaben", passedDraft.Tags);
|
||||||
|
Assert.Equal([student.Id], passedDraft.StudentIds);
|
||||||
|
|
||||||
|
var created = Assert.Single(vorgaenge.GetAll());
|
||||||
|
Assert.Equal("Hausaufgaben", created.Title);
|
||||||
|
Assert.True(Assert.Single(vm.Cases).IsRevealed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleWarningNavigation_KeinPassenderVorgang_LegtNichtsAnBeiAblehnung()
|
||||||
|
{
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
|
||||||
|
vm.Load(student.Id);
|
||||||
|
|
||||||
|
vm.OnConfirmCreateForWarning = _ => Task.FromResult(false);
|
||||||
|
var editDialogCalled = false;
|
||||||
|
vm.OnEditVorgang = (_, _) => { editDialogCalled = true; return Task.FromResult<Vorgang?>(null); };
|
||||||
|
|
||||||
|
await vm.HandleWarningNavigation("Verspätungen", "Verspätungen");
|
||||||
|
|
||||||
|
Assert.False(editDialogCalled);
|
||||||
|
Assert.Empty(vorgaenge.GetAll());
|
||||||
|
Assert.Empty(vm.Cases);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels;
|
||||||
|
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
/// Tests für die Belege hinter den klassenübergreifenden Dashboard-Warnungen: das Detail-Popup
|
||||||
|
/// (StudentWarningDetailViewModel), die Schnellbausteine im Vorgang-Dialog und die
|
||||||
|
/// Dokumentationsvorlagen im schülerbezogenen Vorgänge-Tab. Alle Termine liegen ab
|
||||||
|
/// Schuljahresbeginn, damit die Tests unabhängig vom Ausführungsdatum im laufenden Schuljahr landen.
|
||||||
|
public sealed class StudentWarningEvidenceTests
|
||||||
|
{
|
||||||
|
private readonly Student _student = new() { FirstName = "Anna", LastName = "Beispiel" };
|
||||||
|
private readonly LearningGroup _group = new() { Name = "9c Mathe" };
|
||||||
|
private readonly List<ParticipationSession> _sessions = [];
|
||||||
|
private readonly FakeEntries _entries = new();
|
||||||
|
private readonly DateOnly _start;
|
||||||
|
|
||||||
|
public StudentWarningEvidenceTests()
|
||||||
|
{
|
||||||
|
var sy = new SchoolYearService();
|
||||||
|
_start = sy.SchoolYearStart(sy.CurrentSchoolYear());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void AddEntry(int dayOffset, AttendanceStatus? attendance = null, HomeworkStatus? homework = null)
|
||||||
|
{
|
||||||
|
var session = new ParticipationSession { GroupId = _group.Id, Date = _start.AddDays(dayOffset) };
|
||||||
|
_sessions.Add(session);
|
||||||
|
_entries.Add(new ParticipationEntry
|
||||||
|
{ SessionId = session.Id, StudentId = _student.Id, Attendance = attendance, Homework = homework });
|
||||||
|
}
|
||||||
|
|
||||||
|
private StudentWarningEvidenceService BuildService() => new(new FakeStudents([_student]),
|
||||||
|
new FakeSessions(_sessions), _entries, new FakeGroups([_group]), new SchoolYearService(),
|
||||||
|
new AttendanceBalanceService());
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Build_ZaehltWieDieDashboardWarnungen()
|
||||||
|
{
|
||||||
|
AddEntry(0, AttendanceStatus.Present);
|
||||||
|
AddEntry(1, AttendanceStatus.Excused);
|
||||||
|
AddEntry(2, AttendanceStatus.Unexcused);
|
||||||
|
AddEntry(3, AttendanceStatus.ExcusePending);
|
||||||
|
AddEntry(4, AttendanceStatus.OtherSchoolEvent);
|
||||||
|
AddEntry(5, AttendanceStatus.Late, HomeworkStatus.MissingOpen);
|
||||||
|
AddEntry(6, AttendanceStatus.SignificantlyLate, HomeworkStatus.Completed);
|
||||||
|
|
||||||
|
var e = BuildService().Build(_student.Id);
|
||||||
|
|
||||||
|
Assert.Equal(7, e.Balance.TotalChecked);
|
||||||
|
Assert.Equal(3, e.Absences.Count); // Schulveranstaltung zählt nicht als Fehlzeit
|
||||||
|
Assert.Equal(["A", "U", "E"], e.Absences.Select(a => a.Code)); // neueste zuerst
|
||||||
|
Assert.Equal(2, e.Lateness.Count);
|
||||||
|
Assert.Equal(1, e.SignificantlyLateCount);
|
||||||
|
Assert.Equal("9c Mathe", Assert.Single(e.MissingHomework).GroupName);
|
||||||
|
Assert.Equal("Anna Beispiel", e.StudentNaturalName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void QuickBlocks_NurBausteineMitInhalt()
|
||||||
|
{
|
||||||
|
AddEntry(0, AttendanceStatus.Unexcused);
|
||||||
|
AddEntry(1, AttendanceStatus.Present);
|
||||||
|
|
||||||
|
var blocks = StudentEvidenceText.QuickBlocks(BuildService().Build(_student.Id));
|
||||||
|
|
||||||
|
Assert.Equal(["Fehlquote", "Fehltermine"], blocks.Select(b => b.Label));
|
||||||
|
Assert.Contains("Fehlquote 50 %", blocks[0].Text);
|
||||||
|
Assert.Contains("9c Mathe", blocks[1].Text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void VorgangDialog_InsertQuickBlock_HaengtAnStattZuErsetzen()
|
||||||
|
{
|
||||||
|
var vm = new VorgangDialogViewModel([new StudentOption(_student.Id, "Anna")], null,
|
||||||
|
[new VorgangQuickBlock("Fehlquote", "Stand: 25 %")]) { Description = "Eigene Notiz" };
|
||||||
|
|
||||||
|
vm.InsertQuickBlockCommand.Execute(vm.QuickBlocks[0]);
|
||||||
|
|
||||||
|
Assert.Equal("Eigene Notiz\n\nStand: 25 %", vm.Description);
|
||||||
|
Assert.Equal("Vorgang anlegen", vm.DialogTitle);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Vorlage_ElternanrufUebernimmtZahlenPassendZumVorgangsTag()
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 3; i++) AddEntry(i, AttendanceStatus.Present, HomeworkStatus.MissingOverdue);
|
||||||
|
var vorgang = new Vorgang { Title = "Hausaufgaben", StudentIds = [_student.Id], Tags = ["Hausaufgaben"] };
|
||||||
|
|
||||||
|
var doc = VorgangDocumentationTemplates.Build(VorgangDocumentationTemplates.ParentCall, vorgang,
|
||||||
|
BuildService().Build(_student.Id))!;
|
||||||
|
|
||||||
|
Assert.Equal(DocumentationType.ParentCall, doc.Type);
|
||||||
|
Assert.Equal(_student.Id, doc.StudentId);
|
||||||
|
Assert.StartsWith("Aktueller Stand: 3 nicht bzw. unvollständig erledigte Hausaufgaben", doc.ParentCallData!.Points[0].Text);
|
||||||
|
Assert.DoesNotContain(doc.ParentCallData.Points, p => p.Text.Contains("Fehlquote"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetailPopup_StartetImMonatDesJuengstenBelegsUndZeigtKuerzel()
|
||||||
|
{
|
||||||
|
AddEntry(0, AttendanceStatus.Unexcused);
|
||||||
|
AddEntry(0, AttendanceStatus.Excused); // zweite Stunde am selben Tag: U gewinnt
|
||||||
|
AddEntry(1, AttendanceStatus.Late);
|
||||||
|
|
||||||
|
var vm = new StudentWarningDetailViewModel(AttentionKind.Attendance, BuildService().Build(_student.Id));
|
||||||
|
|
||||||
|
Assert.Equal(new DateOnly(_start.Year, _start.Month, 1), vm.Month);
|
||||||
|
var first = vm.CalendarDays.Single(d => d.Date == _start);
|
||||||
|
Assert.Equal("U", first.SignalCode);
|
||||||
|
Assert.Contains("Krank, entschuldigt", first.Tooltip);
|
||||||
|
Assert.Equal("V", vm.CalendarDays.Single(d => d.Date == _start.AddDays(1)).SignalCode);
|
||||||
|
Assert.False(vm.PreviousMonthCommand.CanExecute(null)); // vor Schuljahresbeginn gibt es nichts
|
||||||
|
Assert.Equal(2, vm.Events.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleWarningNavigation_BelegtBeschreibungMitAktuellemStandVor()
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 4; i++) AddEntry(i, AttendanceStatus.Unexcused);
|
||||||
|
var vm = new StudentVorgaengeViewModel(new FakeVorgangRepository(), new FakeDocumentation(),
|
||||||
|
new FakeStudents([_student]), BuildService());
|
||||||
|
vm.Load(_student.Id);
|
||||||
|
vm.OnConfirmCreateForWarning = _ => Task.FromResult(true);
|
||||||
|
Vorgang? draft = null;
|
||||||
|
vm.OnEditVorgang = (_, editing) => { draft = editing; return Task.FromResult<Vorgang?>(null); };
|
||||||
|
|
||||||
|
await vm.HandleWarningNavigation("Absentismus", "Fehlzeiten");
|
||||||
|
|
||||||
|
Assert.Contains("Fehlquote 100 %", draft!.Description);
|
||||||
|
Assert.Contains("Fehltermine:", draft.Description);
|
||||||
|
Assert.False(vm.IsPersisted(draft));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GemeinsamerVorgang_DokumentationFuerMehrereErscheintAuchBeimZweitenSchueler()
|
||||||
|
{
|
||||||
|
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
|
||||||
|
var students = new FakeStudents([_student, ben]);
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
var vorgang = new Vorgang { Title = "Streit", StudentIds = [_student.Id, ben.Id], Tags = ["Konflikte"] };
|
||||||
|
vorgaenge.Add(vorgang);
|
||||||
|
var documentation = new FakeDocumentation();
|
||||||
|
var vm = new StudentVorgaengeViewModel(vorgaenge, documentation, students);
|
||||||
|
vm.Load(_student.Id);
|
||||||
|
List<StudentOption> offered = [];
|
||||||
|
vm.OnEditDocumentation = (studentId, coStudents, _) =>
|
||||||
|
{
|
||||||
|
offered = coStudents;
|
||||||
|
return Task.FromResult<Documentation?>(new Documentation
|
||||||
|
{
|
||||||
|
StudentId = studentId, AdditionalStudentIds = [ben.Id], Title = "Gespräch mit beiden",
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
await vm.CreateAndLinkDocumentationCommand.ExecuteAsync(Assert.Single(vm.Cases));
|
||||||
|
|
||||||
|
Assert.Equal([_student.Id, ben.Id], offered.Select(o => o.Id));
|
||||||
|
var benView = new StudentVorgaengeViewModel(vorgaenge, documentation, students);
|
||||||
|
benView.Load(ben.Id);
|
||||||
|
var linked = Assert.Single(Assert.Single(benView.Cases).LinkedDocumentation);
|
||||||
|
Assert.Equal("Gespräch mit beiden", linked.Model.Title);
|
||||||
|
Assert.Contains("Muster", linked.StudentName);
|
||||||
|
Assert.Contains("Beispiel", linked.StudentName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task VorlageAusVorgangstab_OeffnetEntwurfUndVerknuepftNachSpeichern()
|
||||||
|
{
|
||||||
|
AddEntry(0, AttendanceStatus.Unexcused);
|
||||||
|
var vorgaenge = new FakeVorgangRepository();
|
||||||
|
var vorgang = new Vorgang { Title = "Fehlzeiten", StudentIds = [_student.Id], Tags = ["Absentismus"] };
|
||||||
|
vorgaenge.Add(vorgang);
|
||||||
|
var documentation = new FakeDocumentation();
|
||||||
|
var vm = new StudentVorgaengeViewModel(vorgaenge, documentation, new FakeStudents([_student]), BuildService());
|
||||||
|
vm.Load(_student.Id);
|
||||||
|
var wasDraft = false;
|
||||||
|
vm.OnEditDocumentation = (_, _, editing) =>
|
||||||
|
{
|
||||||
|
wasDraft = vm.IsNewDocumentationDraft(editing!);
|
||||||
|
return Task.FromResult(editing);
|
||||||
|
};
|
||||||
|
|
||||||
|
var item = Assert.Single(vm.Cases);
|
||||||
|
Assert.True(item.HasDocumentationTemplates);
|
||||||
|
await item.CreateFromTemplateCommand.ExecuteAsync(VorgangDocumentationTemplates.Conversation);
|
||||||
|
|
||||||
|
Assert.True(wasDraft);
|
||||||
|
var saved = Assert.Single(documentation.GetByStudent(_student.Id));
|
||||||
|
Assert.Equal(DocumentationType.Conversation, saved.Type);
|
||||||
|
Assert.Contains("Fehlquote 100 %", saved.Content);
|
||||||
|
Assert.Contains(saved.Id, vorgang.DocumentationIds);
|
||||||
|
Assert.True(Assert.Single(vm.Cases).IsRevealed);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -67,4 +67,94 @@ public sealed class TeachingModeOutstandingHomeworkViewModelTests
|
|||||||
vm.Refresh();
|
vm.Refresh();
|
||||||
Assert.Equal(amelia.FullName, Assert.Single(vm.Rows).StudentName);
|
Assert.Equal(amelia.FullName, Assert.Single(vm.Rows).StudentName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(HomeworkStatus.MissingOpen, "submitted", HomeworkStatus.SubmittedLate)]
|
||||||
|
[InlineData(HomeworkStatus.MissingOpen, "final", HomeworkStatus.MissingOverdue)]
|
||||||
|
[InlineData(HomeworkStatus.MissingOpen, "partial", HomeworkStatus.PartialMissingOverdue)]
|
||||||
|
[InlineData(HomeworkStatus.MissingOverdue, "submitted", HomeworkStatus.SubmittedLate)]
|
||||||
|
[InlineData(HomeworkStatus.PartiallyCompleted, "submitted", HomeworkStatus.PartialSubmittedLate)]
|
||||||
|
[InlineData(HomeworkStatus.PartiallyCompleted, "final", HomeworkStatus.PartialMissingOverdue)]
|
||||||
|
[InlineData(HomeworkStatus.PartialMissingOverdue, "submitted", HomeworkStatus.PartialSubmittedLate)]
|
||||||
|
public void Zeilenaktionen_SetzenPassendenEndstatus(HomeworkStatus start, string action, HomeworkStatus expected)
|
||||||
|
{
|
||||||
|
var (vm, entries, entry) = CreateSingle(start);
|
||||||
|
vm.Refresh();
|
||||||
|
var row = Assert.Single(vm.Rows);
|
||||||
|
|
||||||
|
var command = action switch
|
||||||
|
{
|
||||||
|
"submitted" => row.MarkSubmittedCommand,
|
||||||
|
"final" => row.MarkFinalCommand,
|
||||||
|
_ => row.MarkPartialCommand,
|
||||||
|
};
|
||||||
|
command.Execute(null);
|
||||||
|
|
||||||
|
var saved = entries.GetBySessionAndStudent(entry.SessionId, entry.StudentId)!;
|
||||||
|
Assert.Equal(expected, saved.Homework);
|
||||||
|
Assert.Equal(HomeworkDisplay.CountsAsMissing(expected), saved.HomeworkMissing);
|
||||||
|
Assert.Equal(HomeworkDisplay.CountsAsMissing(expected), vm.Rows.Count == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Zeilenaktionen_BietenNurSinnvolleOptionenAn()
|
||||||
|
{
|
||||||
|
var (vm, _, _) = CreateSingle(HomeworkStatus.MissingOverdue);
|
||||||
|
vm.Refresh();
|
||||||
|
var overdue = Assert.Single(vm.Rows);
|
||||||
|
Assert.False(overdue.CanMarkFinal);
|
||||||
|
Assert.True(overdue.CanMarkPartial);
|
||||||
|
|
||||||
|
(vm, _, _) = CreateSingle(HomeworkStatus.PartiallyCompleted);
|
||||||
|
vm.Refresh();
|
||||||
|
var partial = Assert.Single(vm.Rows);
|
||||||
|
Assert.True(partial.CanMarkFinal);
|
||||||
|
Assert.False(partial.CanMarkPartial);
|
||||||
|
|
||||||
|
(vm, _, _) = CreateSingle(HomeworkStatus.MissingOpen, isReadOnly: true);
|
||||||
|
vm.Refresh();
|
||||||
|
Assert.False(Assert.Single(vm.Rows).CanEdit);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Undo_StelltVorherigenStatusWiederHer()
|
||||||
|
{
|
||||||
|
var (vm, entries, entry) = CreateSingle(HomeworkStatus.MissingOpen);
|
||||||
|
var changed = 0;
|
||||||
|
vm.OnHomeworkChanged = () => changed++;
|
||||||
|
vm.Refresh();
|
||||||
|
Assert.False(vm.UndoCommand.CanExecute(null));
|
||||||
|
|
||||||
|
vm.Rows[0].MarkSubmittedCommand.Execute(null);
|
||||||
|
Assert.Empty(vm.Rows);
|
||||||
|
Assert.NotNull(vm.LastChangeLabel);
|
||||||
|
Assert.True(vm.UndoCommand.CanExecute(null));
|
||||||
|
|
||||||
|
vm.UndoCommand.Execute(null);
|
||||||
|
var saved = entries.GetBySessionAndStudent(entry.SessionId, entry.StudentId)!;
|
||||||
|
Assert.Equal(HomeworkStatus.MissingOpen, saved.Homework);
|
||||||
|
Assert.True(saved.HomeworkMissing);
|
||||||
|
Assert.Single(vm.Rows);
|
||||||
|
Assert.Null(vm.LastChangeLabel);
|
||||||
|
Assert.False(vm.UndoCommand.CanExecute(null));
|
||||||
|
Assert.Equal(2, changed);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (TeachingModeOutstandingHomeworkViewModel Vm, FakeEntries Entries, ParticipationEntry Entry)
|
||||||
|
CreateSingle(HomeworkStatus status, bool isReadOnly = false)
|
||||||
|
{
|
||||||
|
var date = new DateOnly(2026, 9, 25);
|
||||||
|
var group = new LearningGroup { Name = "10c Chemie" };
|
||||||
|
var student = new Student { FirstName = "Ben", LastName = "Muster" };
|
||||||
|
var session = new ParticipationSession { GroupId = group.Id, Date = date.AddDays(-5) };
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var entry = new ParticipationEntry { SessionId = session.Id, StudentId = student.Id,
|
||||||
|
Homework = status, HomeworkMissing = true };
|
||||||
|
entries.Add(entry);
|
||||||
|
var vm = new TeachingModeOutstandingHomeworkViewModel(group.Id, date,
|
||||||
|
new FakeStudents([student]),
|
||||||
|
new FakeMemberships([new GroupMembership { StudentId = student.Id, GroupId = group.Id }]),
|
||||||
|
new FakeSessions([session]), entries, isReadOnly);
|
||||||
|
return (vm, entries, entry);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -187,6 +187,45 @@ public sealed class UntisReportCacheServiceTests
|
|||||||
Assert.Equal(4, handler.Requests.Count); // keine weiteren Anfragen - aus dem Cache bedient
|
Assert.Equal(4, handler.Requests.Count); // keine weiteren Anfragen - aus dem Cache bedient
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetAbsencesAsync_AlterHistorischerBerichtWirdErsetztUndDanachGecacht()
|
||||||
|
{
|
||||||
|
var day = DateOnly.FromDateTime(DateTime.Today).AddDays(-30);
|
||||||
|
var csv = Encoding.UTF8.GetBytes(
|
||||||
|
"Schüler*innen\tKlasse\tDatum\tFehlstd.\tFehlmin.\tFehltage\r\n" +
|
||||||
|
$"Muster Max\t10c\t{day:dd.MM.yy}\t2\t90\t0\r\n");
|
||||||
|
var schoolyears = "{\"result\":[{\"id\":7,\"name\":\"2026/27\",\"startDate\":20260801,\"endDate\":20270731}]}";
|
||||||
|
var handler = new QueueHandler(
|
||||||
|
Json("{\"result\":{\"sessionId\":\"s\"}}"), Json(schoolyears), Json(schoolyears),
|
||||||
|
Json("{\"result\":[{\"id\":874,\"name\":\"10c\"}]}"),
|
||||||
|
Json("{\"data\":{\"finished\":true,\"error\":false,\"reportParams\":\"get=rpt.tmp&name=AbsencePerStudent&format=csv\"}}"),
|
||||||
|
new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(csv) },
|
||||||
|
Json("{\"result\":{}}"));
|
||||||
|
await using var untis = new WebUntisIntegrationService(new HttpClient(handler), TestSupport.BuildWebUntisSettingsService());
|
||||||
|
await untis.ConnectAsync(new WebUntisCredentials("bk-ostvest", "arche.webuntis.com", "lehrkraft", "geheim"));
|
||||||
|
var absences = new FakeUntisAbsenceCache();
|
||||||
|
absences.InsertRange([new UntisAbsenceCacheEntry
|
||||||
|
{
|
||||||
|
ClassName = "10c", StudentName = "Muster Max", Date = Int(day),
|
||||||
|
AbsentPeriods = 2, CountsAsFullDay = true,
|
||||||
|
}]);
|
||||||
|
var states = new FakeUntisCacheFetchStates();
|
||||||
|
states.Save(new UntisCacheFetchState
|
||||||
|
{
|
||||||
|
ClassName = "10c", Kind = UntisCacheKind.Absences,
|
||||||
|
HotWindowFetchedAt = DateTime.UtcNow, ColdCoverageStartDate = Int(day),
|
||||||
|
});
|
||||||
|
var cache = new UntisReportCacheService(untis, absences, new FakeUntisClassRegisterCache(),
|
||||||
|
new FakeUntisStudentRosterCache(), states);
|
||||||
|
|
||||||
|
var first = Assert.Single(await cache.GetAbsencesAsync("10c", day, day));
|
||||||
|
Assert.False(first.CountsAsFullDay);
|
||||||
|
Assert.Equal(2, first.AbsentPeriods);
|
||||||
|
var requestCount = handler.Requests.Count;
|
||||||
|
Assert.False(Assert.Single(await cache.GetAbsencesAsync("10c", day, day)).CountsAsFullDay);
|
||||||
|
Assert.Equal(requestCount, handler.Requests.Count);
|
||||||
|
}
|
||||||
|
|
||||||
private static HttpResponseMessage Json(string json) => new(HttpStatusCode.OK)
|
private static HttpResponseMessage Json(string json) => new(HttpStatusCode.OK)
|
||||||
{
|
{
|
||||||
Content = new StringContent(json, Encoding.UTF8, "application/json"),
|
Content = new StringContent(json, Encoding.UTF8, "application/json"),
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
using LehrerApp.Desktop.Views.Shared;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
/// Tests für Standardformulierungen, schülerabhängige Bausteine im Vorgang-Dialog, den WebUntis-Stand
|
||||||
|
/// der Klassenlehrer-Vorgänge und die Wochentags-Ausrichtung des kompakten Monatskalenders.
|
||||||
|
public sealed class VorgangBausteineTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void KompakterKalender_BeginntInDerSpalteDesWochentags()
|
||||||
|
{
|
||||||
|
// 1. September 2026 ist ein Dienstag -> eine Leerzelle (Montag) davor.
|
||||||
|
var days = Enumerable.Range(1, 30).Select(d => new ClassTeacherCompactCalendarDay(
|
||||||
|
new DateOnly(2026, 9, d), "", "#00000000", "", false)).ToList();
|
||||||
|
|
||||||
|
var cells = CompactMonthCalendar.BuildCells(days);
|
||||||
|
|
||||||
|
Assert.True(cells[0].IsPlaceholder);
|
||||||
|
Assert.Equal(new DateOnly(2026, 9, 1), cells[1].Day!.Date);
|
||||||
|
Assert.Equal(31, cells.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void KompakterKalender_MonatsbeginnAmMontag_OhneLeerzelle()
|
||||||
|
{
|
||||||
|
var days = new[] { new ClassTeacherCompactCalendarDay(new DateOnly(2026, 6, 1), "", "", "", false) };
|
||||||
|
Assert.False(CompactMonthCalendar.BuildCells(days)[0].IsPlaceholder);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Standardformulierung_WirdAlsZeileAngehaengt()
|
||||||
|
{
|
||||||
|
var vm = new VorgangDialogViewModel([new StudentOption(Guid.NewGuid(), "Anna")], null,
|
||||||
|
phraseBlocks: VorgangPhraseBlocks.ForStudent(new DateOnly(2026, 9, 26))) { Description = "Notiz" };
|
||||||
|
|
||||||
|
vm.InsertPhraseCommand.Execute(vm.PhraseBlocks.First(p => p.Label == "Klassenleitung informiert"));
|
||||||
|
|
||||||
|
Assert.Equal("Notiz\n26.09.2026: Klassenleitung informiert.", vm.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SchuelerBausteine_FolgenDerAuswahlImDialog()
|
||||||
|
{
|
||||||
|
var anna = new StudentOption(Guid.NewGuid(), "Anna");
|
||||||
|
var ben = new StudentOption(Guid.NewGuid(), "Ben");
|
||||||
|
var vm = new VorgangDialogViewModel([anna, ben], null,
|
||||||
|
studentQuickBlocks: ids => ids.Select(id => new VorgangQuickBlock(id == anna.Id ? "A" : "B", "")).ToList());
|
||||||
|
|
||||||
|
Assert.False(vm.HasQuickBlocks);
|
||||||
|
vm.StudentOptions[1].IsSelected = true;
|
||||||
|
Assert.Equal(["B"], vm.QuickBlocks.Select(b => b.Label));
|
||||||
|
vm.StudentOptions[0].IsSelected = true;
|
||||||
|
Assert.Equal(["A", "B"], vm.QuickBlocks.Select(b => b.Label));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ClassAbsenceDaySummaryRow Absence(DateOnly date, string name, int periods, bool unexcused,
|
||||||
|
bool fullDay = false, string reason = "Krankheit") => new(date, name, null, periods, periods * 45,
|
||||||
|
["M"], [1], [unexcused ? "nicht entschuldigt" : "entschuldigt"], [reason], null, null, fullDay);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void KlassenlehrerStand_ZaehltFehlzeitenVerspaetungenUndKlassenbuch()
|
||||||
|
{
|
||||||
|
var student = new StudentOption(Guid.NewGuid(), "Beispiel Anna");
|
||||||
|
var today = new DateOnly(2026, 9, 26);
|
||||||
|
var absences = new[]
|
||||||
|
{
|
||||||
|
Absence(today.AddDays(-3), "Anna Beispiel", 6, unexcused: true, fullDay: true),
|
||||||
|
Absence(today.AddDays(-5), "Anna Beispiel", 2, unexcused: false),
|
||||||
|
Absence(today.AddDays(-6), "Anna Beispiel", 0, unexcused: false, reason: "Verspätung"),
|
||||||
|
Absence(today.AddDays(-3), "Ben Fremd", 6, unexcused: true),
|
||||||
|
};
|
||||||
|
var register = new[]
|
||||||
|
{
|
||||||
|
new ClassTeacherClassRegisterRow(today.AddDays(-2), "D", "Anna Beispiel", "MUE", "Hausaufgaben fehlen", "Negativ", null),
|
||||||
|
new ClassTeacherClassRegisterRow(today.AddDays(-1), "E", "Anna Beispiel", "SCH", "Lob", "Positiv", null),
|
||||||
|
};
|
||||||
|
|
||||||
|
var facts = ClassTeacherStudentFacts.Build(student, "Anna Beispiel", "2026/27", today, absences, register);
|
||||||
|
|
||||||
|
Assert.Equal(8, facts.AbsentPeriods);
|
||||||
|
Assert.Equal(1, facts.UnexcusedDays);
|
||||||
|
Assert.Equal(2, facts.PartialAbsentPeriods);
|
||||||
|
Assert.Equal(0, facts.UnexcusedPartialPeriods);
|
||||||
|
Assert.Single(facts.LateDays);
|
||||||
|
Assert.Equal(1, facts.NegativeRegisterCount);
|
||||||
|
Assert.Single(facts.HomeworkEntries);
|
||||||
|
Assert.Contains("1 ganzer Fehltag und 2 weitere Fehlstunden", facts.AbsenceShort);
|
||||||
|
|
||||||
|
var labels = facts.QuickBlocks(withName: true).Select(b => b.Label).ToList();
|
||||||
|
Assert.Contains("Fehlzeiten · Beispiel Anna", labels);
|
||||||
|
|
||||||
|
var ctx = facts.TemplateContext(new Vorgang { Title = "Fehlzeiten", Tags = ["Absentismus"] });
|
||||||
|
Assert.Equal([facts.AbsenceShort], ctx.SituationLines);
|
||||||
|
var letter = VorgangDocumentationTemplates.Build(VorgangDocumentationTemplates.ParentLetter,
|
||||||
|
new Vorgang { Title = "Fehlzeiten", Tags = ["Absentismus"] }, ctx)!;
|
||||||
|
Assert.StartsWith("Sehr geehrte Erziehungsberechtigte von Anna Beispiel", letter.ParentLetterData!.DraftContent);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void KlassenlehrerStand_UnentschuldigteFehlstundeWirdNichtAlsFehltagBezeichnet()
|
||||||
|
{
|
||||||
|
var student = new StudentOption(Guid.NewGuid(), "Beispiel Anna");
|
||||||
|
var today = new DateOnly(2026, 9, 28);
|
||||||
|
var facts = ClassTeacherStudentFacts.Build(student, "Anna Beispiel", "2026/27", today,
|
||||||
|
[Absence(today.AddDays(-4), "Anna Beispiel", 1, unexcused: true)], []);
|
||||||
|
|
||||||
|
Assert.Equal(0, facts.FullDays);
|
||||||
|
Assert.Equal(0, facts.UnexcusedDays);
|
||||||
|
Assert.Equal(1, facts.PartialAbsentPeriods);
|
||||||
|
Assert.Equal(1, facts.UnexcusedPartialPeriods);
|
||||||
|
Assert.Contains("0 ganze Fehltage und 1 weitere Fehlstunde", facts.AbsenceShort);
|
||||||
|
Assert.Contains("unentschuldigt: 0 ganze Tage, 1 Fehlstunde", facts.AbsenceShort);
|
||||||
|
Assert.Contains("1 Fehlstunde · Unentschuldigt", facts.AbsenceBlock);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Vorlage_KlassenleitungInformieren()
|
||||||
|
{
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
var ctx = new VorgangTemplateContext(id, "Anna Beispiel", new DateOnly(2026, 9, 26), ["Fehlquote 25 %"],
|
||||||
|
new Dictionary<string, VorgangSnapshot>());
|
||||||
|
|
||||||
|
var doc = VorgangDocumentationTemplates.Build(VorgangDocumentationTemplates.InformClassTeacher,
|
||||||
|
new Vorgang { Title = "Fehlzeiten" }, ctx)!;
|
||||||
|
|
||||||
|
Assert.Equal(DocumentationType.Conversation, doc.Type);
|
||||||
|
Assert.Equal(["Klassenleitung"], doc.Participants);
|
||||||
|
Assert.Contains("Klassenleitung am 26.09.2026 informiert über:\n- Fehlquote 25 %", doc.Content);
|
||||||
|
Assert.Equal(id, doc.StudentId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Planning;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class WebUntisTimetableImportTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task Load_IsReadOnly_AndSaveUpdatesOnlyLessonIdsByDefault()
|
||||||
|
{
|
||||||
|
await using var fixture = new Fixture();
|
||||||
|
await fixture.Vm.LoadCommand.ExecuteAsync(null);
|
||||||
|
Assert.Null(fixture.Group.WebUntisLessonId);
|
||||||
|
Assert.Null(fixture.Settings.TeacherUntisId);
|
||||||
|
Assert.Single(fixture.Slots.GetAll());
|
||||||
|
Assert.Equal(38926, Assert.Single(fixture.Vm.Rows).LessonId);
|
||||||
|
fixture.Vm.SaveCommand.Execute(null);
|
||||||
|
Assert.True(fixture.Vm.Saved);
|
||||||
|
Assert.Equal(38926, fixture.Group.WebUntisLessonId);
|
||||||
|
Assert.Equal(DayOfWeek.Friday, Assert.Single(fixture.Slots.GetAll()).Weekday);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(false, 2)]
|
||||||
|
[InlineData(true, 1)]
|
||||||
|
public async Task TimetableUpdates_OnlyRemoveOldSlotsWhenExplicitlySelected(bool replace, int expected)
|
||||||
|
{
|
||||||
|
await using var fixture = new Fixture();
|
||||||
|
await fixture.Vm.LoadCommand.ExecuteAsync(null);
|
||||||
|
fixture.Vm.UpdateLessonIds = false;
|
||||||
|
fixture.Vm.UpdateTimetable = true;
|
||||||
|
fixture.Vm.ReplaceTimetable = replace;
|
||||||
|
fixture.Vm.SaveCommand.Execute(null);
|
||||||
|
Assert.True(fixture.Vm.Saved);
|
||||||
|
Assert.Null(fixture.Group.WebUntisLessonId);
|
||||||
|
Assert.Equal(expected, fixture.Slots.GetAll().Count);
|
||||||
|
Assert.Contains(fixture.Slots.GetAll(), slot => slot.Weekday == DayOfWeek.Monday);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ConflictingLessonIds_BlockAllChanges_UntilExcluded()
|
||||||
|
{
|
||||||
|
await using var fixture = new Fixture();
|
||||||
|
await fixture.Vm.LoadCommand.ExecuteAsync(null);
|
||||||
|
fixture.Vm.Rows.Add(new WebUntisTimetableRow
|
||||||
|
{
|
||||||
|
Weekday = DayOfWeek.Tuesday, PeriodNumber = 1, TimeLabel = "07:50", UntisLabel = "7a",
|
||||||
|
SuggestedGroupName = "7a", LessonId = 999, SelectedGroup = fixture.Vm.Rows[0].SelectedGroup,
|
||||||
|
});
|
||||||
|
fixture.Vm.UpdateTimetable = true;
|
||||||
|
fixture.Vm.SaveCommand.Execute(null);
|
||||||
|
Assert.False(fixture.Vm.Saved);
|
||||||
|
Assert.Null(fixture.Group.WebUntisLessonId);
|
||||||
|
Assert.Single(fixture.Slots.GetAll());
|
||||||
|
Assert.Contains("Mehrere Unterrichtsnummern", fixture.Vm.Status);
|
||||||
|
fixture.Vm.Rows[1].ApplyLessonId = false;
|
||||||
|
fixture.Vm.SaveCommand.Execute(null);
|
||||||
|
Assert.True(fixture.Vm.Saved);
|
||||||
|
Assert.Equal(38926, fixture.Group.WebUntisLessonId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SaveWithoutLoadedWeek_DoesNotClearTimetable()
|
||||||
|
{
|
||||||
|
await using var fixture = new Fixture();
|
||||||
|
fixture.Vm.UpdateTimetable = fixture.Vm.ReplaceTimetable = true;
|
||||||
|
fixture.Vm.SaveCommand.Execute(null);
|
||||||
|
Assert.False(fixture.Vm.Saved);
|
||||||
|
Assert.Single(fixture.Slots.GetAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Fixture : IAsyncDisposable
|
||||||
|
{
|
||||||
|
public LearningGroup Group { get; } = new() { Name = "7a" };
|
||||||
|
public FakeTimetableSlots Slots { get; } = new();
|
||||||
|
public WebUntisSettingsService Settings { get; } = TestSupport.BuildWebUntisSettingsService();
|
||||||
|
private readonly WebUntisIntegrationService _service;
|
||||||
|
public WebUntisTimetableImportViewModel Vm { get; }
|
||||||
|
public Fixture()
|
||||||
|
{
|
||||||
|
Settings.SetApiCredentials(new("school", "example.webuntis.com", "teacher", "password"));
|
||||||
|
_service = new(new HttpClient(new Handler()), Settings);
|
||||||
|
Slots.Add(new() { Weekday = DayOfWeek.Friday, PeriodNumber = 4, GroupId = Group.Id });
|
||||||
|
Vm = new(_service, Settings, Slots, new FakeGroups([Group]))
|
||||||
|
{
|
||||||
|
SelectedTeacher = new(89, "Teacher", null, null, null, true, []),
|
||||||
|
WeekDate = new DateTimeOffset(2026, 10, 5, 0, 0, 0, TimeSpan.Zero),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public ValueTask DisposeAsync() => _service.DisposeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Handler : HttpMessageHandler
|
||||||
|
{
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
|
||||||
|
{
|
||||||
|
var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(token);
|
||||||
|
var json = request.RequestUri!.AbsolutePath.Contains("weekly/data")
|
||||||
|
? """{"data":{"result":{"data":{"elementPeriods":{"89":[{"id":2013854,"lessonId":38926},{"id":2013854,"lessonId":38926}]}}}}}"""
|
||||||
|
: body.Contains("authenticate") ? """{"result":{"sessionId":"s"}}"""
|
||||||
|
: body.Contains("getTimetable") ? """{"result":[{"id":2013854,"date":20261005,"startTime":750,"endTime":835,"kl":[{"id":4,"name":"7a"}],"te":[],"su":[],"ro":[]}]}"""
|
||||||
|
: body.Contains("getTimegridUnits") ? """{"result":[{"day":1,"timeUnits":[{"name":"1","startTime":750,"endTime":835}]}]}"""
|
||||||
|
: """{"result":{}}""";
|
||||||
|
return new(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ using LehrerApp.Desktop.ViewModels.Planning;
|
|||||||
using LehrerApp.Desktop.ViewModels.Students;
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
using LehrerApp.Desktop.ViewModels.Workload;
|
using LehrerApp.Desktop.ViewModels.Workload;
|
||||||
using LehrerApp.Desktop.Views;
|
using LehrerApp.Desktop.Views;
|
||||||
|
using LehrerApp.Desktop.Views.Shared;
|
||||||
using LehrerApp.Desktop.Views.Workload;
|
using LehrerApp.Desktop.Views.Workload;
|
||||||
using LehrerApp.Sync;
|
using LehrerApp.Sync;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -234,10 +235,12 @@ public class App : Application
|
|||||||
var dash = Services.GetRequiredService<DashboardViewModel>();
|
var dash = Services.GetRequiredService<DashboardViewModel>();
|
||||||
dash.OnNavigateToGroup = id => main.NavigateToGroupDetail(id);
|
dash.OnNavigateToGroup = id => main.NavigateToGroupDetail(id);
|
||||||
dash.OnNavigateToStudent = id => main.NavigateToStudent(id);
|
dash.OnNavigateToStudent = id => main.NavigateToStudent(id);
|
||||||
|
dash.OnNavigateToStudentCase = (id, tag, title) => main.NavigateToStudentCase(id, tag, title);
|
||||||
dash.OnNavigateToLesson = id => main.NavigateToGroupDetail(id, 3); // Tab "Mitarbeit"
|
dash.OnNavigateToLesson = id => main.NavigateToGroupDetail(id, 3); // Tab "Mitarbeit"
|
||||||
dash.OnNavigateToExam = id => main.NavigateToGroupDetail(id, 4); // Tab "Klausuren"
|
dash.OnNavigateToExam = id => main.NavigateToGroupDetail(id, 4); // Tab "Klausuren"
|
||||||
dash.OnNavigateToUnplannedLesson = id => main.NavigateToGroupDetail(id, 6); // Tab "Planung"
|
dash.OnNavigateToUnplannedLesson = id => main.NavigateToGroupDetail(id, 6); // Tab "Planung"
|
||||||
dash.OnAddMissingTeachingTime = item => ShowMissingTeachingTimeDialog(item, dash);
|
dash.OnAddMissingTeachingTime = item => ShowMissingTeachingTimeDialog(item, dash);
|
||||||
|
dash.OnPickSnoozeDuration = ShowSnoozeDurationDialog;
|
||||||
|
|
||||||
var examsOverview = Services.GetRequiredService<ViewModels.Exams.ExamsOverviewViewModel>();
|
var examsOverview = Services.GetRequiredService<ViewModels.Exams.ExamsOverviewViewModel>();
|
||||||
examsOverview.OnNavigateToGroups = () => main.NavigateToCommand.Execute(NavItem.Groups);
|
examsOverview.OnNavigateToGroups = () => main.NavigateToCommand.Execute(NavItem.Groups);
|
||||||
@@ -293,6 +296,16 @@ public class App : Application
|
|||||||
Services.GetRequiredService<WorkTaskListViewModel>().Load();
|
Services.GetRequiredService<WorkTaskListViewModel>().Load();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static async Task<int?> ShowSnoozeDurationDialog(string message)
|
||||||
|
{
|
||||||
|
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime
|
||||||
|
{ MainWindow: { } owner }) return null;
|
||||||
|
|
||||||
|
var vm = new SnoozeDurationDialogInfo { Message = message };
|
||||||
|
var dialog = new SnoozeDurationDialog { DataContext = vm };
|
||||||
|
return await dialog.ShowDialog<int?>(owner);
|
||||||
|
}
|
||||||
|
|
||||||
private static async Task ShowMissingTeachingTimeDialog(MissingTeachingTimeItem item, DashboardViewModel dashboard)
|
private static async Task ShowMissingTeachingTimeDialog(MissingTeachingTimeItem item, DashboardViewModel dashboard)
|
||||||
{
|
{
|
||||||
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime
|
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime
|
||||||
|
|||||||
@@ -122,6 +122,7 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton<PdfExportService>();
|
services.AddSingleton<PdfExportService>();
|
||||||
services.AddSingleton<ITemplateLoader, TemplateLoader>();
|
services.AddSingleton<ITemplateLoader, TemplateLoader>();
|
||||||
services.AddSingleton<ITemplateRenderer, QuestTemplateRenderer>();
|
services.AddSingleton<ITemplateRenderer, QuestTemplateRenderer>();
|
||||||
|
services.AddSingleton<ITemplateBatchRenderer, QuestTemplateRenderer>();
|
||||||
services.AddSingleton(_ => new TemplateStore(appData));
|
services.AddSingleton(_ => new TemplateStore(appData));
|
||||||
services.AddSingleton(_ => new WorksheetTemplateStore(new TemplateStore(appData, subfolder: "worksheet-template-packages")));
|
services.AddSingleton(_ => new WorksheetTemplateStore(new TemplateStore(appData, subfolder: "worksheet-template-packages")));
|
||||||
|
|
||||||
@@ -156,6 +157,7 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton<IStudentRepository, StudentRepository>();
|
services.AddSingleton<IStudentRepository, StudentRepository>();
|
||||||
services.AddSingleton<IGroupRepository, GroupRepository>();
|
services.AddSingleton<IGroupRepository, GroupRepository>();
|
||||||
services.AddSingleton<ISeatingPlanRepository, SeatingPlanRepository>();
|
services.AddSingleton<ISeatingPlanRepository, SeatingPlanRepository>();
|
||||||
|
services.AddSingleton<IStudentGroupPlanRepository, StudentGroupPlanRepository>();
|
||||||
services.AddSingleton<ITrashRepository, TrashRepository>();
|
services.AddSingleton<ITrashRepository, TrashRepository>();
|
||||||
services.AddSingleton<IGroupMembershipRepository, GroupMembershipRepository>();
|
services.AddSingleton<IGroupMembershipRepository, GroupMembershipRepository>();
|
||||||
services.AddSingleton<IExamRepository, ExamRepository>();
|
services.AddSingleton<IExamRepository, ExamRepository>();
|
||||||
@@ -163,11 +165,13 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton<IGradeRepository, GradeRepository>();
|
services.AddSingleton<IGradeRepository, GradeRepository>();
|
||||||
services.AddSingleton<IGradingSchemeRepository, GradingSchemeRepository>();
|
services.AddSingleton<IGradingSchemeRepository, GradingSchemeRepository>();
|
||||||
services.AddSingleton<IReportGradeRepository, ReportGradeRepository>();
|
services.AddSingleton<IReportGradeRepository, ReportGradeRepository>();
|
||||||
|
services.AddSingleton<IInterimGradeRepository, InterimGradeRepository>();
|
||||||
services.AddSingleton<IGradingKeyTemplateRepository, GradingKeyTemplateRepository>();
|
services.AddSingleton<IGradingKeyTemplateRepository, GradingKeyTemplateRepository>();
|
||||||
services.AddSingleton<IUnitRepository, UnitRepository>();
|
services.AddSingleton<IUnitRepository, UnitRepository>();
|
||||||
services.AddSingleton<ILessonRepository, LessonRepository>();
|
services.AddSingleton<ILessonRepository, LessonRepository>();
|
||||||
services.AddSingleton<IDocumentationRepository, DocumentationRepository>();
|
services.AddSingleton<IDocumentationRepository, DocumentationRepository>();
|
||||||
services.AddSingleton<IVorgangRepository, VorgangRepository>();
|
services.AddSingleton<IVorgangRepository, VorgangRepository>();
|
||||||
|
services.AddSingleton<IDashboardWarningSnoozeRepository, DashboardWarningSnoozeRepository>();
|
||||||
services.AddSingleton<IWorkTaskRepository, WorkTaskRepository>();
|
services.AddSingleton<IWorkTaskRepository, WorkTaskRepository>();
|
||||||
services.AddSingleton<ITimeEntryRepository, TimeEntryRepository>();
|
services.AddSingleton<ITimeEntryRepository, TimeEntryRepository>();
|
||||||
services.AddSingleton<IParticipationSessionRepository, ParticipationSessionRepository>();
|
services.AddSingleton<IParticipationSessionRepository, ParticipationSessionRepository>();
|
||||||
@@ -206,7 +210,9 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton(_ => new DashboardSettingsService(appData));
|
services.AddSingleton(_ => new DashboardSettingsService(appData));
|
||||||
services.AddSingleton(_ => new PatternScoreSettingsService(appData));
|
services.AddSingleton(_ => new PatternScoreSettingsService(appData));
|
||||||
services.AddSingleton(_ => new WindowSettingsService(appData));
|
services.AddSingleton(_ => new WindowSettingsService(appData));
|
||||||
|
services.AddSingleton(_ => new ExamGradingSettingsService(appData));
|
||||||
services.AddSingleton(_ => new AppearanceSettingsService(appData));
|
services.AddSingleton(_ => new AppearanceSettingsService(appData));
|
||||||
|
services.AddSingleton(_ => new TeacherSettingsService(appData));
|
||||||
services.AddSingleton<PlanningExchangeService>();
|
services.AddSingleton<PlanningExchangeService>();
|
||||||
|
|
||||||
// ── KI-Unterstützung (4.5.9, optional – nur wenn in den Einstellungen aktiviert) ──────
|
// ── KI-Unterstützung (4.5.9, optional – nur wenn in den Einstellungen aktiviert) ──────
|
||||||
@@ -232,6 +238,7 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton<GroupMembershipTools>();
|
services.AddSingleton<GroupMembershipTools>();
|
||||||
services.AddSingleton<LetterTemplateTools>();
|
services.AddSingleton<LetterTemplateTools>();
|
||||||
services.AddSingleton<StudentAttendanceCalendarService>();
|
services.AddSingleton<StudentAttendanceCalendarService>();
|
||||||
|
services.AddSingleton<StudentReportService>();
|
||||||
services.AddSingleton<CompetencyTools>();
|
services.AddSingleton<CompetencyTools>();
|
||||||
services.AddSingleton<GroupTools>();
|
services.AddSingleton<GroupTools>();
|
||||||
services.AddSingleton<ParticipationTools>();
|
services.AddSingleton<ParticipationTools>();
|
||||||
@@ -357,6 +364,8 @@ public static class AppBootstrapper
|
|||||||
// Transient: neue Instanz pro Navigation (für Detailseiten)
|
// Transient: neue Instanz pro Navigation (für Detailseiten)
|
||||||
services.AddTransient<GroupDetailViewModel>();
|
services.AddTransient<GroupDetailViewModel>();
|
||||||
services.AddTransient<StudentDetailViewModel>();
|
services.AddTransient<StudentDetailViewModel>();
|
||||||
|
services.AddTransient<StudentWarningEvidenceService>();
|
||||||
|
services.AddTransient<StudentVorgaengeViewModel>();
|
||||||
services.AddTransient<GroupOverviewViewModel>();
|
services.AddTransient<GroupOverviewViewModel>();
|
||||||
services.AddTransient<ParticipationTabViewModel>();
|
services.AddTransient<ParticipationTabViewModel>();
|
||||||
services.AddTransient<GradeOverviewTabViewModel>();
|
services.AddTransient<GradeOverviewTabViewModel>();
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
{"v":"5.7.8","fr":25,"ip":0,"op":25,"w":1080,"h":1080,"nm":"[ pecah Asset - Games Roda Keberuntungan ] EMOS - Juni","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"link-tengah Outlines","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[538.46,407.962,0],"ix":2,"l":2},"a":{"a":0,"k":[65.18,65.182,0],"ix":1,"l":2},"s":{"a":0,"k":[100,100,100],"ix":6,"l":2}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-1.586,31.425],[-31.425,-1.586],[1.586,-31.426],[31.425,1.588]],"o":[[1.588,-31.423],[31.426,1.588],[-1.589,31.425],[-31.425,-1.586]],"v":[[-56.9,-2.875],[2.873,-56.901],[56.9,2.873],[-2.874,56.899]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[-1.668,33.037],[33.036,1.668],[1.668,-33.037],[-33.036,-1.671]],"o":[[1.67,-33.037],[-33.037,-1.668],[-1.67,33.036],[33.037,1.668]],"v":[[59.817,3.02],[3.021,-59.818],[-59.817,-3.022],[-3.022,59.818]],"c":true},"ix":2},"nm":"Path 2","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"mm","mm":1,"nm":"Merge Paths 1","mn":"ADBE Vector Filter - Merge","hd":false},{"ty":"fl","c":{"a":0,"k":[0.2196078431372549,0.28627450980392155,0.8196078431372549,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[65.181,65.182],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":6,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-28.146,-8.66],[8.66,-28.146],[28.147,8.66],[-7.333,25.672]],"o":[[28.146,8.661],[-8.66,28.144],[-28.146,-8.661],[8.09,-28.315]],"v":[[14.668,-49.317],[50.116,15.469],[-14.669,49.694],[-50.116,-13.869]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[-30.651,-9.431],[-9.431,30.652],[30.651,9.432],[9.431,-30.652]],"o":[[30.652,9.432],[9.432,-30.652],[-30.652,-9.431],[-9.431,30.651]],"v":[[-17.078,55.5],[55.499,17.076],[17.077,-55.501],[-55.5,-17.077]],"c":true},"ix":2},"nm":"Path 2","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"mm","mm":1,"nm":"Merge Paths 1","mn":"ADBE Vector Filter - Merge","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[65.181,65.182],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 2","np":6,"cix":2,"bm":0,"ix":2,"mn":"ADBE Vector Group","hd":false},{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-1.55,30.701],[30.701,1.55],[1.55,-30.701],[-30.702,-1.552]],"o":[[1.552,-30.701],[-30.701,-1.55],[-1.552,30.701],[30.701,1.55]],"v":[[55.589,2.806],[2.808,-55.59],[-55.588,-2.809],[-2.808,55.59]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0.3686274509803922,0.4470588235294118,0.8941176470588236,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[65.18,65.182],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 3","np":4,"cix":2,"bm":0,"ix":3,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":25,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"Arrow Outlines","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":4,"s":[-17]},{"t":7,"s":[10]}],"ix":10,"x":"var $bm_rt;\n$bm_rt = loopOut('cycle', 0);"},"p":{"a":0,"k":[882.284,387.765,0],"ix":2,"l":2},"a":{"a":0,"k":[90.2,66.694,0],"ix":1,"l":2},"s":{"a":0,"k":[100,100,100],"ix":6,"l":2}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.184,-20.641],[-20.642,-1.186],[-1.183,20.641],[20.643,1.183]],"o":[[-1.185,20.643],[20.643,1.184],[1.186,-20.644],[-20.643,-1.185]],"v":[[-37.376,-2.145],[-2.144,37.377],[37.375,2.146],[2.145,-37.375]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0.2196078431372549,0.28627450980392155,0.8196078431372549,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[112.538,63.94],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k"Line truncated
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"v":"5.6.6","fr":60,"ip":60,"op":120,"w":600,"h":600,"nm":"development and submittals","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"person-top-face-outlinne Outlines","parent":8,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[73.415,-16.001,0],"ix":2},"a":{"a":0,"k":[33.313,42.52,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[4.515,0],[2.745,1.593],[0,10.18],[-5.843,10.003],[-8.233,4.781],[-6.463,-3.719],[0,-10.181],[5.754,-10.093],[8.234,-4.692]],"o":[[-3.276,0],[-6.551,-3.718],[0,-9.561],[5.754,-10.004],[8.853,-5.046],[6.551,3.718],[0,9.561],[-5.843,10.092],[-5.223,2.921]],"v":[[-13.102,41.52],[-22.221,39.13],[-32.313,17.529],[-23.283,-12.836],[-1.505,-35.765],[22.22,-37.801],[32.313,-16.2],[23.372,14.165],[1.593,37.094]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[2.214,0],[4.161,-2.301],[5.312,-9.118],[0,-8.41],[-4.516,-2.656],[-6.816,3.895],[-0.089,0],[-5.222,9.119],[0,8.498],[4.603,2.656]],"o":[[-3.452,0],[-7.348,4.25],[-5.312,9.118],[0,7.879],[4.514,2.656],[0.089,0],[7.17,-4.16],[5.224,-9.118],[0,-7.88],[-1.682,-0.973]],"v":[[13.013,-33.995],[1.505,-30.454],[-18.06,-9.738],[-26.205,17.529],[-19.21,33.818],[-1.594,31.782],[-1.416,31.693],[17.882,11.066],[26.027,-16.2],[18.945,-32.49]],"c":true},"ix":2},"nm":"Path 2","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"mm","mm":1,"nm":"Merge Paths 1","mn":"ADBE Vector Filter - Merge","hd":false},{"ty":"st","c":{"a":0,"k":[0,0,0,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":0.4,"ix":5},"lc":1,"lj":1,"ml":10,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0,0,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[33.313,42.52],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":5,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":300,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"person-top-face-face Outlines","parent":8,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[73.324,-15.34,0],"ix":2},"a":{"a":0,"k":[29.464,39.069,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-8.056,4.692],[-5.223,9.119],[0,9.295],[5.312,3.099],[8.056,-4.692],[5.223,-9.207],[0,-9.384],[-5.312,-3.098]],"o":[[8.056,-4.692],[5.312,-9.118],[0,-9.296],[-5.312,-3.098],[-8.056,4.692],[-5.312,9.119],[0,9.296],[5.312,2.833]],"v":[[0,33.773],[20.627,11.995],[29.214,-16.775],[20.627,-35.722],[0,-33.684],[-20.627,-11.818],[-29.214,17.041],[-20.627,35.986]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[29.464,39.07],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":300,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"person-top-body-front-outline Outlines","parent":8,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[73.461,58.935,0],"ix":2},"a":{"a":0,"k":[53.718,49.646,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0.531,0],[0.443,0.266],[0,1.151],[-8.764,15.05],[-13.633,7.967],[-10.358,-5.932],[-0.886,-14.431],[0.974,-0.531],[0,0]],"o":[[-0.62,0],[-0.973,-0.531],[0.886,-14.784],[9.649,-16.732],[14.253,-8.233],[9.471,5.488],[0.088,1.151],[0,0],[-0.62,0.354]],"v":[[-49.619,48.646],[-51.214,48.204],[-52.719,45.371],[-37.846,-0.929],[-1.638,-39.173],[36.607,-42.714],[52.63,-11.906],[51.125,-9.074],[-48.025,48.204]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[4.249,0],[7.437,-4.249],[9.119,-15.758],[1.682,-12.305],[0,0],[7.171,4.161]],"o":[[-6.286,0],[-12.837,7.436],[-7.082,12.306],[0,0],[-1.063,-11.332],[-3.364,-1.948]],"v":[[22.089,-40.147],[1.372,-33.773],[-32.622,2.169],[-46.079,39.971],[46.257,-13.324],[33.508,-37.314]],"c":true},"ix":2},"nm":"Path 2","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"mm","mm":1,"nm":"Merge Paths 1","mn":"ADBE Vector Filter - Merge","hd":false},{"ty":"st","c":{"a":0,"k":[0,0,0,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":0.4,"ix":5},"lc":1,"lj":1,"ml":10,"bm":0,"nm":"Stroke 1",Line truncated
|
||||||
@@ -18,6 +18,7 @@
|
|||||||
<PackageReference Include="Avalonia.Themes.Fluent" />
|
<PackageReference Include="Avalonia.Themes.Fluent" />
|
||||||
<PackageReference Include="Avalonia.Fonts.Inter" />
|
<PackageReference Include="Avalonia.Fonts.Inter" />
|
||||||
<PackageReference Include="Avalonia.Controls.DataGrid" />
|
<PackageReference Include="Avalonia.Controls.DataGrid" />
|
||||||
|
<PackageReference Include="Avalonia.Labs.Lottie" />
|
||||||
<PackageReference Include="CommunityToolkit.Mvvm" />
|
<PackageReference Include="CommunityToolkit.Mvvm" />
|
||||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||||
<PackageReference Include="QuestPDF" />
|
<PackageReference Include="QuestPDF" />
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
|
public sealed record AiAccountBalance([property: JsonRequired] decimal BalanceUsd, decimal? BalanceEur);
|
||||||
@@ -146,25 +146,49 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
|||||||
return result?.Token ?? throw new AiBackendException("Unerwartete Antwort des KI-Dienstes.");
|
return result?.Token ?? throw new AiBackendException("Unerwartete Antwort des KI-Dienstes.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<decimal> GetBalanceAsync(string token)
|
public async Task<decimal> GetBalanceAsync(string token) =>
|
||||||
{
|
(await GetAccountBalanceAsync(token)).BalanceUsd;
|
||||||
using var req = new HttpRequestMessage(HttpMethod.Get, "status.php");
|
|
||||||
req.Headers.Authorization = new("Bearer", token);
|
|
||||||
|
|
||||||
|
public async Task<AiAccountBalance> GetAccountBalanceAsync(string token)
|
||||||
|
{
|
||||||
|
using var resp = await GetAccountResponseAsync("status.php", token);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await resp.Content.ReadFromJsonAsync<AiAccountBalance>(JsonOptions)
|
||||||
|
?? throw new AiBackendException("Das Guthaben des KI-Dienstes konnte nicht verarbeitet werden.");
|
||||||
|
}
|
||||||
|
catch (JsonException)
|
||||||
|
{
|
||||||
|
throw new AiBackendException("Das Guthaben des KI-Dienstes konnte nicht verarbeitet werden.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AiUsageReport> GetUsageAsync(string token)
|
||||||
|
{
|
||||||
|
using var resp = await GetAccountResponseAsync("api/v1/usage.php?days=28", token);
|
||||||
|
return AiUsageReport.Parse(await resp.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<HttpResponseMessage> GetAccountResponseAsync(string path, string token)
|
||||||
|
{
|
||||||
|
using var req = new HttpRequestMessage(HttpMethod.Get, path);
|
||||||
|
req.Headers.Authorization = new("Bearer", token);
|
||||||
HttpResponseMessage resp;
|
HttpResponseMessage resp;
|
||||||
try { resp = await http.SendAsync(req); }
|
try { resp = await http.SendAsync(req); }
|
||||||
catch (HttpRequestException)
|
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException)
|
||||||
{
|
{
|
||||||
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte Internetverbindung prüfen.");
|
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte später erneut versuchen.");
|
||||||
}
|
}
|
||||||
|
if (resp.IsSuccessStatusCode) return resp;
|
||||||
if (resp.StatusCode == HttpStatusCode.Unauthorized)
|
var status = resp.StatusCode;
|
||||||
throw new AiBackendException("Anmeldung abgelaufen. Bitte in den Einstellungen erneut anmelden.");
|
resp.Dispose();
|
||||||
if (!resp.IsSuccessStatusCode)
|
throw new AiBackendException(status switch
|
||||||
throw new AiBackendException("Guthaben konnte nicht abgerufen werden.");
|
{
|
||||||
|
HttpStatusCode.Unauthorized => "Anmeldung abgelaufen. Bitte in den Einstellungen erneut anmelden.",
|
||||||
var result = await resp.Content.ReadFromJsonAsync<BalanceResult>(JsonOptions);
|
HttpStatusCode.NotFound when path.StartsWith("api/v1/usage") =>
|
||||||
return result?.BalanceUsd ?? 0m;
|
"Dieses Backend stellt noch keine Verbrauchsübersicht bereit.",
|
||||||
|
_ => "Die Kontodaten des KI-Dienstes konnten nicht abgerufen werden."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Rein (nur Repository-Lesezugriffe, kein Netzwerk) — testbar mit Fakes.</summary>
|
/// <summary>Rein (nur Repository-Lesezugriffe, kein Netzwerk) — testbar mit Fakes.</summary>
|
||||||
@@ -695,7 +719,6 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
|||||||
}
|
}
|
||||||
|
|
||||||
private class LoginResult { public string Token { get; set; } = ""; }
|
private class LoginResult { public string Token { get; set; } = ""; }
|
||||||
private class BalanceResult { public decimal BalanceUsd { get; set; } }
|
|
||||||
private class BackendErrorResult
|
private class BackendErrorResult
|
||||||
{
|
{
|
||||||
public string? Error { get; set; }
|
public string? Error { get; set; }
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
|
/// <summary>Verbrauch einer Aktion im Zeitraum, z. B. „Text korrigieren“ oder eine Planung der LehrerApp (alle Apps am selben Backend).</summary>
|
||||||
|
/// <param name="Operation">Funktion der Arbeitsblatt-API; null bei Aktionen anderer Apps.</param>
|
||||||
|
/// <param name="ChargedEur">Nur, wenn für jeden Aufruf der Euro-Gegenwert dokumentiert ist; sonst null (der Dienst schätzt nichts).</param>
|
||||||
|
public sealed record AiUsageGroup(string ActionId, string Label, string? Operation, int Calls, decimal ChargedUsd, decimal? ChargedEur);
|
||||||
|
|
||||||
|
/// <summary>Ein berechneter Aufruf. <see cref="At"/> ist die Uhrzeit der Datenbank des Dienstes, ohne Zeitzone.</summary>
|
||||||
|
public sealed record AiUsageEntry(DateTime At, string ActionId, string Label, string? Operation, string Status, decimal ChargedUsd, decimal? ChargedEur);
|
||||||
|
|
||||||
|
/// <param name="SpellcheckGranted">Ob die Rechtschreibprüfung über das Backend freigegeben ist; null, wenn der Dienst es nicht meldet.</param>
|
||||||
|
public sealed record AiUsageReport(int Days, DateTime From, DateTime To, int Calls, decimal ChargedUsd, decimal? ChargedEur,
|
||||||
|
IReadOnlyList<AiUsageGroup> ByAction, IReadOnlyList<AiUsageEntry> Entries, bool EntriesTruncated, bool? SpellcheckGranted)
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Liest die Antwort von <c>api/v1/usage.php</c>. Unbekannte zusätzliche Felder werden übergangen (der Dienst darf wachsen), fehlende oder
|
||||||
|
/// unplausible Pflichtfelder sind ein Fehler.
|
||||||
|
/// </summary>
|
||||||
|
public static AiUsageReport Parse(string json)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 16 });
|
||||||
|
var root = document.RootElement;
|
||||||
|
Need(root.GetProperty("apiVersion").GetString() == "1" && root.GetProperty("schema").GetString() == "lehrerbackend.usage.v1");
|
||||||
|
var period = root.GetProperty("period");
|
||||||
|
var days = period.GetProperty("days").GetInt32();
|
||||||
|
var totals = root.GetProperty("totals");
|
||||||
|
var groups = new List<AiUsageGroup>();
|
||||||
|
foreach (var item in root.GetProperty("byAction").EnumerateArray())
|
||||||
|
{
|
||||||
|
Need(groups.Count < 256);
|
||||||
|
groups.Add(new(Text(item, "actionId", 64), Text(item, "label", 200), Operation(item), item.GetProperty("calls").GetInt32(),
|
||||||
|
RequiredMoney(item, "chargedUsd"), Money(item, "chargedEur")));
|
||||||
|
}
|
||||||
|
var entries = new List<AiUsageEntry>();
|
||||||
|
foreach (var item in root.GetProperty("entries").EnumerateArray())
|
||||||
|
{
|
||||||
|
Need(entries.Count < 1000);
|
||||||
|
entries.Add(new(Date(item.GetProperty("at").GetString()), Text(item, "actionId", 64), Text(item, "label", 200), Operation(item), Text(item, "status", 32),
|
||||||
|
RequiredMoney(item, "chargedUsd"), Money(item, "chargedEur")));
|
||||||
|
}
|
||||||
|
bool? spellcheck = root.TryGetProperty("features", out var features) && features.TryGetProperty("spellcheck", out var flag) && flag.ValueKind is JsonValueKind.True or JsonValueKind.False
|
||||||
|
? flag.GetBoolean() : null;
|
||||||
|
var calls = totals.GetProperty("calls").GetInt32();
|
||||||
|
Need(days is >= 1 and <= 366 && calls >= 0 && groups.All(g => g.Calls >= 0 && g.ChargedUsd >= 0 && g.ChargedEur is null or >= 0) && entries.All(e => e.ChargedUsd >= 0));
|
||||||
|
return new(days, Date(period.GetProperty("from").GetString()), Date(period.GetProperty("to").GetString()), calls, RequiredMoney(totals, "chargedUsd"), Money(totals, "chargedEur"),
|
||||||
|
groups, entries, root.GetProperty("entriesTruncated").GetBoolean(), spellcheck);
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is JsonException or InvalidOperationException or KeyNotFoundException or FormatException or ArgumentException or OverflowException)
|
||||||
|
{ throw new AiBackendException("Die Verbrauchsdaten des KI-Dienstes konnten nicht verarbeitet werden."); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Need(bool condition) { if (!condition) throw new FormatException(); }
|
||||||
|
|
||||||
|
private static string Text(JsonElement item, string name, int max)
|
||||||
|
{
|
||||||
|
var value = item.GetProperty(name).GetString();
|
||||||
|
Need(!string.IsNullOrWhiteSpace(value) && value.Length <= max);
|
||||||
|
return value!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Operation(JsonElement item) =>
|
||||||
|
item.TryGetProperty("operation", out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
||||||
|
|
||||||
|
private static decimal RequiredMoney(JsonElement item, string name) =>
|
||||||
|
Money(item, name) ?? throw new FormatException();
|
||||||
|
|
||||||
|
private static decimal? Money(JsonElement item, string name)
|
||||||
|
{
|
||||||
|
if (!item.TryGetProperty(name, out var value) || value.ValueKind == JsonValueKind.Null) return null;
|
||||||
|
// Dezimaltext mit höchstens sechs Nachkommastellen wie im ganzen Vertrag, nie eine Fließkommazahl
|
||||||
|
var text = value.GetString();
|
||||||
|
Need(text is not null && System.Text.RegularExpressions.Regex.IsMatch(text, @"^\d{1,9}(\.\d{1,6})?$"));
|
||||||
|
return decimal.Parse(text!, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateTime Date(string? text)
|
||||||
|
{
|
||||||
|
Need(DateTime.TryParseExact(text, "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _));
|
||||||
|
return DateTime.ParseExact(text!, "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
|
/// <summary>Platzhalterwerte für Klausur-Deckblätter (Vorlagen mit
|
||||||
|
/// <c>report-type=exam-cover</c>): die Standardwerte der Elternbriefe (Student.*, Group.Name, …)
|
||||||
|
/// plus Exam.*, Result.* und die Punktetabelle. Alle Punktwerte gelten für die Fassung, die der
|
||||||
|
/// Schüler geschrieben hat.</summary>
|
||||||
|
public static class ExamCoverPlaceholderBuilder
|
||||||
|
{
|
||||||
|
/// <summary>Stehen statt Punkten bzw. Note auf dem Blatt, solange nichts eingetragen wird —
|
||||||
|
/// als Linie zum Ausfüllen von Hand.</summary>
|
||||||
|
public const string BlankPoints = "_________", BlankGrade = "_____";
|
||||||
|
|
||||||
|
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
|
||||||
|
|
||||||
|
/// <param name="result">Ergebnis des Schülers oder null. Punkte und Note werden nur
|
||||||
|
/// eingetragen, wenn <paramref name="fillResults"/> gesetzt und das Ergebnis korrigiert ist.</param>
|
||||||
|
/// <param name="studentNiveau">Niveau des Schülers in dieser Lerngruppe, falls die Arbeit
|
||||||
|
/// selbst keinem Niveau zugeordnet ist.</param>
|
||||||
|
/// <param name="title">Titel für das Deckblatt, falls er vom internen Klausurtitel abweichen
|
||||||
|
/// soll; null oder leer nimmt den Klausurtitel.</param>
|
||||||
|
public static Dictionary<string, PlaceholderValue> Build(Exam exam, LearningGroup group, string subjectName,
|
||||||
|
Student student, ExamResult? result, bool fillResults, GradingService grading, LoadedTemplate template,
|
||||||
|
DateOnly today, Niveau? studentNiveau = null, string teacherAbbreviation = "",
|
||||||
|
string? title = null, Exam? original = null, ExamResult? originalResult = null,
|
||||||
|
InterimGrade? interim = null)
|
||||||
|
{
|
||||||
|
var tasks = exam.Tasks.OrderBy(t => t.Nr).ToList();
|
||||||
|
var variant = result?.Variant ?? ExamVariant.A;
|
||||||
|
var maximum = ExamScoringService.Maximum(tasks, variant);
|
||||||
|
var filled = fillResults && ExamCoverSheetService.IsCorrected(result);
|
||||||
|
|
||||||
|
var values = LetterPlaceholderBuilder.BuildStandardValues(student, contact: null, group, today, "", "");
|
||||||
|
values["Group.GradeLevel"] = new TextValue(group.GradeLevel > 0 ? group.GradeLevel.ToString() : "");
|
||||||
|
values["Subject.Name"] = new TextValue(subjectName);
|
||||||
|
values["Exam.Title"] = new TextValue(string.IsNullOrWhiteSpace(title) ? exam.Title : title.Trim());
|
||||||
|
values["Exam.Date"] = new DateValue(exam.Date);
|
||||||
|
values["Exam.Number"] = new TextValue(exam.ExamNumber?.ToString() ?? "");
|
||||||
|
values["Exam.Kind"] = new TextValue(exam.Kind.Label());
|
||||||
|
values["Exam.Niveau"] = new TextValue(exam.Niveau.HasValue ? NiveauDisplay.ToName(exam.Niveau) : "");
|
||||||
|
values["Exam.Course"] = new TextValue(CourseLabel(group, exam.Niveau ?? studentNiveau));
|
||||||
|
values["Teacher.Abbreviation"] = new TextValue(teacherAbbreviation.Trim());
|
||||||
|
values["Exam.Variant"] = new TextValue(tasks.Any(t => t.Variant is not null) ? variant.ToString() : "");
|
||||||
|
values["Exam.MaxPoints"] = new TextValue(Format(maximum));
|
||||||
|
values["Exam.ApprovalDate"] = new TextValue(Format(exam.ApprovalGrantedAt));
|
||||||
|
values["Exam.AnnouncedDate"] = new TextValue(Format(exam.AnnouncedAt));
|
||||||
|
values["Exam.ReturnDate"] = new TextValue(Format(exam.ReturnedAt));
|
||||||
|
values["Result.Points"] = new TextValue(filled ? Format(result!.TotalPoints) : BlankPoints);
|
||||||
|
values["Result.Percent"] = new TextValue(filled && maximum > 0
|
||||||
|
? (result!.TotalPoints / maximum).ToString("0 %", German) : "");
|
||||||
|
values["Result.Grade"] = new TextValue(filled
|
||||||
|
? result!.Grade ?? grading.CalculateGrade(result.TotalPoints, maximum, exam.GradingKey) : BlankGrade);
|
||||||
|
|
||||||
|
// Ohne Box in der Vorlage gibt es nichts zu zeichnen (die Tabelle ist optional).
|
||||||
|
values[ExamPointsTableDrawingBuilder.PlaceholderName] =
|
||||||
|
LetterPlaceholderBuilder.FindDeclaredDrawingBox(template, ExamPointsTableDrawingBuilder.PlaceholderName) is { } box
|
||||||
|
? ExamPointsTableDrawingBuilder.Build(
|
||||||
|
ExamCoverSheetService.Columns(tasks, variant, filled ? result!.Points : null),
|
||||||
|
box.Width, box.MillimeterScale)
|
||||||
|
: new DrawingValue([], 0);
|
||||||
|
values[ReportTextDrawing.RepeatInfo] = DrawingBoxLocator.Find(template, ReportTextDrawing.RepeatInfo) is null
|
||||||
|
? new DrawingValue([], 0) : GradeReportDrawingBuilder.Repeat(exam, original, originalResult, template);
|
||||||
|
values[ReportTextDrawing.InterimGrades] = interim is null
|
||||||
|
? new DrawingValue([], 0) : GradeReportDrawingBuilder.Interim(interim, template);
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"E-Kurs" / "G-Kurs" für die äußere Differenzierung; leer im Klassenverband und
|
||||||
|
/// ohne E-/G-Zuordnung.</summary>
|
||||||
|
public static string CourseLabel(LearningGroup group, Niveau? niveau) =>
|
||||||
|
group.Type == GroupType.Class ? "" : niveau switch
|
||||||
|
{
|
||||||
|
Niveau.E => "E-Kurs",
|
||||||
|
Niveau.G => "G-Kurs",
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Format(double value) => value.ToString("0.##", German);
|
||||||
|
private static string Format(DateOnly? date) => date?.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) ?? "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
using Avalonia.Controls;
|
||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using LehrerApp.Desktop.Views.Groups;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
|
/// <summary>Öffnet den Deckblatt-Dialog zu einer Klausur — ein Einstieg für die Klausuren-
|
||||||
|
/// Hauptseite und den Klausuren-Tab der Lerngruppe.</summary>
|
||||||
|
public static class ExamCoverSheetDialogs
|
||||||
|
{
|
||||||
|
public static async Task ShowAsync(Control source, Exam exam)
|
||||||
|
{
|
||||||
|
var group = App.Services.GetRequiredService<IGroupRepository>().GetById(exam.GroupId);
|
||||||
|
if (group is null || TopLevel.GetTopLevel(source) is not Window owner) return;
|
||||||
|
var subject = group.SubjectId is { } subjectId
|
||||||
|
? App.Services.GetRequiredService<ISubjectRepository>().GetById(subjectId)?.Name ?? ""
|
||||||
|
: "";
|
||||||
|
var vm = new ExamCoverSheetDialogViewModel(exam, group, subject,
|
||||||
|
App.Services.GetRequiredService<IStudentRepository>(),
|
||||||
|
App.Services.GetRequiredService<IGroupMembershipRepository>(),
|
||||||
|
App.Services.GetRequiredService<IExamResultRepository>(),
|
||||||
|
App.Services.GetRequiredService<GradingService>(),
|
||||||
|
[App.Services.GetRequiredService<TemplateStore>(), App.Services.GetRequiredService<WorksheetTemplateStore>().Store],
|
||||||
|
App.Services.GetRequiredService<ITemplateBatchRenderer>(),
|
||||||
|
App.Services.GetRequiredService<TeacherSettingsService>().LoadAbbreviation(),
|
||||||
|
App.Services.GetRequiredService<IExamRepository>(),
|
||||||
|
App.Services.GetRequiredService<IInterimGradeRepository>());
|
||||||
|
await new ExamCoverSheetDialog { DataContext = vm }.ShowDialog(owner);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
|
/// <summary>Brücke von den Klausurdaten zur Punktetabelle des Deckblatts. Gezeichnet wird in
|
||||||
|
/// <see cref="ExamPointsTableDrawing"/> (Vorlagenbibliothek), damit der Vorlagen-Designer dieselbe
|
||||||
|
/// Tabelle in der Vorschau zeigt.</summary>
|
||||||
|
public static class ExamPointsTableDrawingBuilder
|
||||||
|
{
|
||||||
|
public const string PlaceholderName = ExamPointsTableDrawing.PlaceholderName;
|
||||||
|
|
||||||
|
public static DrawingValue Build(IReadOnlyList<ExamCoverTaskColumn> columns, float contentWidth = 170,
|
||||||
|
float millimeterScale = 1) =>
|
||||||
|
ExamPointsTableDrawing.Build(
|
||||||
|
columns.Select(c => new ExamPointsTableColumn(c.Number, c.MaxPoints, c.IsBonus, c.AchievedPoints)).ToList(),
|
||||||
|
contentWidth, millimeterScale);
|
||||||
|
|
||||||
|
public static int ColumnsPerBlock(float contentWidth, float millimeterScale = 1) =>
|
||||||
|
ExamPointsTableDrawing.ColumnsPerBlock(contentWidth, millimeterScale);
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
|
public static class GradeReportDrawingBuilder
|
||||||
|
{
|
||||||
|
public static DrawingValue Interim(InterimGrade grade, LoadedTemplate template) =>
|
||||||
|
Text(template, ReportTextDrawing.InterimGrades, "Vorläufiger Notenzwischenstand",
|
||||||
|
[
|
||||||
|
$"Stichtag: {grade.Date:dd.MM.yyyy} · {grade.Occasion}",
|
||||||
|
$"Mündlich: {Value(grade.OralValue)}",
|
||||||
|
$"Schriftlich: {Value(grade.WrittenValue)}",
|
||||||
|
$"Vorläufige Zeugnisnote: {Value(grade.OverallValue)}",
|
||||||
|
"Dieser Zwischenstand ist keine festgeschriebene Zeugnisnote.",
|
||||||
|
]);
|
||||||
|
|
||||||
|
public static DrawingValue Repeat(Exam exam, Exam? original, ExamResult? originalResult,
|
||||||
|
LoadedTemplate template)
|
||||||
|
{
|
||||||
|
if (exam.RepeatOfExamId is null) return new DrawingValue([], 0);
|
||||||
|
if (original is null || original.Id != exam.RepeatOfExamId || original.GroupId != exam.GroupId)
|
||||||
|
throw new InvalidDataException("Die verknüpfte erste Arbeit ist nicht verfügbar.");
|
||||||
|
var rule = exam.IsSupportWork ? "Die Förderarbeit ersetzt die erste Arbeit. Liegen beide Noten vor, zählt die erste Arbeit."
|
||||||
|
: exam.IsMakeUp ? "Die Nachschreibarbeit ersetzt die versäumte erste Arbeit. Liegen beide Noten vor, zählt die erste Arbeit."
|
||||||
|
: exam.RepeatGradeRule switch
|
||||||
|
{
|
||||||
|
RepeatGradeRule.Repeat => "Für die Bewertung zählt die Note der Wiederholungsarbeit.",
|
||||||
|
RepeatGradeRule.Original => "Für die Bewertung zählt die Note der ersten Arbeit.",
|
||||||
|
_ => "Für die Bewertung zählt die bessere Note aus beiden Arbeiten.",
|
||||||
|
};
|
||||||
|
var grade = originalResult?.Grade;
|
||||||
|
if (string.IsNullOrWhiteSpace(grade) && ExamCoverSheetService.IsCorrected(originalResult))
|
||||||
|
grade = new GradingService().CalculateGrade(originalResult!.TotalPoints,
|
||||||
|
ExamScoringService.Maximum(original.Tasks, originalResult.Variant), original.GradingKey);
|
||||||
|
var firstGrade = originalResult is { Absent: true } ? "abwesend" : Value(grade);
|
||||||
|
return Text(template, ReportTextDrawing.RepeatInfo,
|
||||||
|
exam.IsSupportWork ? "Förderarbeit" : exam.IsMakeUp ? "Nachschreibarbeit" : "Wiederholungsarbeit",
|
||||||
|
[$"Erste Arbeit: {original.Title} vom {original.Date:dd.MM.yyyy}",
|
||||||
|
$"Note der ersten Arbeit: {firstGrade}", rule]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static DrawingValue Text(LoadedTemplate template, string name, string title, IEnumerable<string> paragraphs)
|
||||||
|
{
|
||||||
|
if (DrawingBoxLocator.Find(template, name) is not { } box) return new DrawingValue([], 0);
|
||||||
|
return ReportTextDrawing.Build(title, paragraphs, box.Width, box.MillimeterScale, box.Height, box.IsFixed);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Value(string? value) => string.IsNullOrWhiteSpace(value) ? "nicht erfasst" : value;
|
||||||
|
}
|
||||||
@@ -51,34 +51,8 @@ public static class LetterPlaceholderBuilder
|
|||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>Tatsächliche DRAWBOX/FLOWDRAWBOX-Größe eines Platzhalters (in der Maßeinheit der
|
/// <summary>Siehe <see cref="DrawingBoxLocator"/> — dort liegt die Suche, damit auch der
|
||||||
/// Vorlage) plus dem Umrechnungsfaktor "1mm in dieser Maßeinheit". DrawingValue-Builder wie
|
/// Vorlagen-Designer sie nutzen kann.</summary>
|
||||||
/// <see cref="StudentAttendanceCalendarDrawingBuilder"/> entwerfen ihr Raster in Millimetern;
|
|
||||||
/// ohne MillimeterScale bliebe das bei einer in "pt" (statt "mm") deklarierten Vorlage viel zu
|
|
||||||
/// klein (1 "mm-Einheit" würde als 1pt ≈ 0.35mm gerendert). IsFixed unterscheidet DRAWBOX (feste,
|
|
||||||
/// nicht umbrechende Box - Inhalt, der die Höhe sprengt, wird von QuestTemplateRenderer
|
|
||||||
/// stillschweigend am unteren Rand abgeschnitten statt umzubrechen) von FLOWDRAWBOX (fließt bei
|
|
||||||
/// Bedarf automatisch auf weitere Seiten, siehe DrawingElementRenderer.Slice) - nur bei
|
|
||||||
/// IsFixed=true darf/muss ein Builder seine Höhe an Height anpassen.</summary>
|
|
||||||
public readonly record struct DeclaredDrawingBox(float Width, float Height, float MillimeterScale, bool IsFixed);
|
|
||||||
|
|
||||||
public static DeclaredDrawingBox? FindDeclaredDrawingBox(LoadedTemplate template, string placeholderName) =>
|
public static DeclaredDrawingBox? FindDeclaredDrawingBox(LoadedTemplate template, string placeholderName) =>
|
||||||
FindDeclaredDrawingBox(template.Layout, placeholderName) ??
|
DrawingBoxLocator.Find(template, placeholderName);
|
||||||
(template.ContinuationLayout is not null ? FindDeclaredDrawingBox(template.ContinuationLayout, placeholderName) : null);
|
|
||||||
|
|
||||||
private static DeclaredDrawingBox? FindDeclaredDrawingBox(TemplateLayout layout, string placeholderName)
|
|
||||||
{
|
|
||||||
var box = layout.Elements.Concat(layout.PageTemplates.SelectMany(p => p.Elements))
|
|
||||||
.Concat(layout.ContentFlows.SelectMany(f => f.Elements))
|
|
||||||
.Select(e => e switch
|
|
||||||
{
|
|
||||||
DrawBoxElement draw when draw.Placeholder == placeholderName => ((float Width, float Height, bool IsFixed)?)(draw.Width, draw.Height, true),
|
|
||||||
FlowDrawBoxElement flow when flow.Placeholder == placeholderName => (flow.Width, flow.Height, false),
|
|
||||||
_ => null,
|
|
||||||
})
|
|
||||||
.FirstOrDefault(b => b is not null);
|
|
||||||
if (box is null) return null;
|
|
||||||
var millimeterScale = UnitConverter.Points(1, "mm") / UnitConverter.Points(1, layout.Unit);
|
|
||||||
return new DeclaredDrawingBox(box.Value.Width, box.Value.Height, millimeterScale, box.Value.IsFixed);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -17,6 +17,7 @@ public class GroupMembershipTools(
|
|||||||
[Description("Schüler-ID.")] Guid studentId,
|
[Description("Schüler-ID.")] Guid studentId,
|
||||||
[Description("Lerngruppen-ID.")] Guid groupId,
|
[Description("Lerngruppen-ID.")] Guid groupId,
|
||||||
[Description("Niveau: E, G oder Foerder. Unverändert lassen: weglassen.")] Niveau? niveau = null,
|
[Description("Niveau: E, G oder Foerder. Unverändert lassen: weglassen.")] Niveau? niveau = null,
|
||||||
|
[Description("Förderschüler-Markierung (auch ohne Niveaudifferenzierung der Gruppe). Unverändert lassen: weglassen.")] bool? isSupportStudent = null,
|
||||||
[Description("Zeitraum: FullYear, H1Only, H2Only oder Custom. Unverändert lassen: weglassen.")] MembershipPeriod? period = null,
|
[Description("Zeitraum: FullYear, H1Only, H2Only oder Custom. Unverändert lassen: weglassen.")] MembershipPeriod? period = null,
|
||||||
[Description("Beitrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? joinedAt = null,
|
[Description("Beitrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? joinedAt = null,
|
||||||
[Description("Austrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? leftAt = null,
|
[Description("Austrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? leftAt = null,
|
||||||
@@ -34,6 +35,7 @@ public class GroupMembershipTools(
|
|||||||
|
|
||||||
var changes = new StringBuilder();
|
var changes = new StringBuilder();
|
||||||
if (niveau is not null && niveau != target.Niveau) { changes.AppendLine($"Niveau: {NiveauName(target.Niveau)} → {NiveauName(niveau)}"); target.Niveau = niveau; }
|
if (niveau is not null && niveau != target.Niveau) { changes.AppendLine($"Niveau: {NiveauName(target.Niveau)} → {NiveauName(niveau)}"); target.Niveau = niveau; }
|
||||||
|
if (isSupportStudent is not null && isSupportStudent != target.IsSupportStudent) { changes.AppendLine($"Förderschüler: {(target.IsSupportStudent ? "ja" : "nein")} → {(isSupportStudent.Value ? "ja" : "nein")}"); target.IsSupportStudent = isSupportStudent.Value; }
|
||||||
if (period is not null && period != target.Period) { changes.AppendLine($"Zeitraum: {target.Period} → {period}"); target.Period = period.Value; }
|
if (period is not null && period != target.Period) { changes.AppendLine($"Zeitraum: {target.Period} → {period}"); target.Period = period.Value; }
|
||||||
if (joinedAt is not null && joinedAt != target.JoinedAt) { changes.AppendLine($"Beitritt: {target.JoinedAt:dd.MM.yyyy} → {joinedAt:dd.MM.yyyy}"); target.JoinedAt = joinedAt; }
|
if (joinedAt is not null && joinedAt != target.JoinedAt) { changes.AppendLine($"Beitritt: {target.JoinedAt:dd.MM.yyyy} → {joinedAt:dd.MM.yyyy}"); target.JoinedAt = joinedAt; }
|
||||||
if (leftAt is not null && leftAt != target.LeftAt) { changes.AppendLine($"Austritt: {target.LeftAt:dd.MM.yyyy} → {leftAt:dd.MM.yyyy}"); target.LeftAt = leftAt; }
|
if (leftAt is not null && leftAt != target.LeftAt) { changes.AppendLine($"Austritt: {target.LeftAt:dd.MM.yyyy} → {leftAt:dd.MM.yyyy}"); target.LeftAt = leftAt; }
|
||||||
@@ -57,6 +59,7 @@ public class GroupMembershipTools(
|
|||||||
{
|
{
|
||||||
Id = m.Id, StudentId = m.StudentId, GroupId = m.GroupId, AddedOn = m.AddedOn,
|
Id = m.Id, StudentId = m.StudentId, GroupId = m.GroupId, AddedOn = m.AddedOn,
|
||||||
Period = m.Period, JoinedAt = m.JoinedAt, LeftAt = m.LeftAt, Niveau = m.Niveau,
|
Period = m.Period, JoinedAt = m.JoinedAt, LeftAt = m.LeftAt, Niveau = m.Niveau,
|
||||||
|
IsSupportStudent = m.IsSupportStudent,
|
||||||
};
|
};
|
||||||
|
|
||||||
private static string NiveauName(Niveau? n) => n switch
|
private static string NiveauName(Niveau? n) => n switch
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ public class LetterTemplateTools(
|
|||||||
public List<LetterTemplateDto> ListLetterTemplates()
|
public List<LetterTemplateDto> ListLetterTemplates()
|
||||||
{
|
{
|
||||||
var result = new List<LetterTemplateDto>();
|
var result = new List<LetterTemplateDto>();
|
||||||
foreach (var installed in templates.GetTemplates())
|
foreach (var installed in templates.GetTemplates().Where(x => !x.IsExamCover && !x.IsStudentReport))
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -151,7 +151,7 @@ public static class StudentAttendanceCalendarDrawingBuilder
|
|||||||
y = gridStartY + 11 * k + 9 * k + maxWeeks * cellHeight + designTrailingGapY * k;
|
y = gridStartY + 11 * k + 9 * k + maxWeeks * cellHeight + designTrailingGapY * k;
|
||||||
|
|
||||||
commands.Add(new DrawStringEx(0, y, 8 * k, contentWidthDesign,
|
commands.Add(new DrawStringEx(0, y, 8 * k, contentWidthDesign,
|
||||||
"U unentschuldigt · A abwesend · V verspätet · E entschuldigt · ! Klassenbuch",
|
"U/E/A ganztägig · T teilweise · G gegangen · V verspätet · ! Klassenbuch",
|
||||||
DrawingTextAlignment.AlignLeft, 6.5f * finalScale, Color: "#6B7280"));
|
DrawingTextAlignment.AlignLeft, 6.5f * finalScale, Color: "#6B7280"));
|
||||||
return new DrawingValue(commands, y + 9 * k);
|
return new DrawingValue(commands, y + 9 * k);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
|
public sealed record StudentReportOptions(DateOnly From, DateOnly To, InterimGrade? Interim,
|
||||||
|
bool IncludeInterim = true, bool IncludeParticipation = true, bool IncludeCompetencies = true,
|
||||||
|
bool IncludeHomework = true, bool IncludeDocumentation = true, bool IncludeConfidential = false,
|
||||||
|
string Comment = "");
|
||||||
|
|
||||||
|
/// <summary>Stellt die vorhandenen Bewertungen eines Schülers für eine Lerngruppe zusammen.
|
||||||
|
/// Die Berechnungen stammen aus denselben Diensten wie die interaktiven Auswertungen.</summary>
|
||||||
|
public sealed class StudentReportService(
|
||||||
|
IParticipationSessionRepository sessions, IParticipationRepository entries,
|
||||||
|
IParticipationAspectRepository aspects, IExamRepository exams, IExamResultRepository results,
|
||||||
|
IGradeRepository grades, IGroupMembershipRepository memberships,
|
||||||
|
ICompetencyDomainRepository domains, IDocumentationRepository documentation,
|
||||||
|
GradingService grading, CompetencyAnalysisService competencies)
|
||||||
|
{
|
||||||
|
public Dictionary<string, PlaceholderValue> Build(Student student, LearningGroup group,
|
||||||
|
LoadedTemplate template, StudentReportOptions options)
|
||||||
|
{
|
||||||
|
if (options.From > options.To) throw new InvalidDataException("Das Ende des Berichtszeitraums liegt vor dem Beginn.");
|
||||||
|
var values = LetterPlaceholderBuilder.BuildStandardValues(student, null, group, DateOnly.FromDateTime(DateTime.Today), "", "");
|
||||||
|
values["Report.Period"] = new TextValue($"{options.From:dd.MM.yyyy} - {options.To:dd.MM.yyyy}");
|
||||||
|
values["Report.Comment"] = new MultilineValue(options.Comment);
|
||||||
|
foreach (var name in StudentReportTemplate.Drawings) values[name] = new DrawingValue([], 0);
|
||||||
|
if (options.IncludeInterim && Uses(ReportTextDrawing.InterimGrades))
|
||||||
|
{
|
||||||
|
var interim = options.Interim;
|
||||||
|
if (interim is null || interim.StudentId != student.Id || interim.GroupId != group.Id
|
||||||
|
|| interim.Date < options.From || interim.Date > options.To)
|
||||||
|
throw new InvalidDataException("Bitte einen gespeicherten Zwischenstand dieses Schülers im Berichtszeitraum auswählen oder den Baustein abwählen.");
|
||||||
|
values[ReportTextDrawing.InterimGrades] = GradeReportDrawingBuilder.Interim(interim, template);
|
||||||
|
}
|
||||||
|
|
||||||
|
var membership = memberships.GetByStudentAndGroup(student.Id, group.Id);
|
||||||
|
bool Within(DateOnly date) => date >= options.From && date <= options.To
|
||||||
|
&& (membership is null || GroupMembershipService.IsActiveOn(membership, date));
|
||||||
|
var groupSessions = sessions.GetByGroup(group.Id).Where(s => Within(s.Date)).OrderBy(s => s.Date).ToList();
|
||||||
|
var bySession = groupSessions.ToDictionary(s => s.Id);
|
||||||
|
var studentEntries = entries.GetByStudent(student.Id).Where(e => bySession.ContainsKey(e.SessionId)).ToList();
|
||||||
|
var applicableAspects = aspects.GetDefaults().Concat(aspects.GetByGroup(group.Id))
|
||||||
|
.GroupBy(a => a.Key).Select(g => g.Last()).ToList();
|
||||||
|
|
||||||
|
if (options.IncludeParticipation && Uses(StudentReportTemplate.Participation))
|
||||||
|
{
|
||||||
|
var timeline = new ParticipationTimelineBuilder(sessions, entries, aspects, exams, results, grades,
|
||||||
|
membership is null ? new Dictionary<Guid, GroupMembership>() : new() { [student.Id] = membership },
|
||||||
|
grading, group.Id, group.GradingSystem);
|
||||||
|
var points = timeline.BuildPoints(student.Id).Where(p => !p.IsExam && Within(p.Date)).ToList();
|
||||||
|
List<ReportChartSeries> series = [new("Gewichtete Mitarbeit", "#6C5CE7",
|
||||||
|
points.Where(p => p.WeightedValue.HasValue).Select(p => new ReportChartPoint(p.Date, p.WeightedValue!.Value)).ToList())];
|
||||||
|
string[] colors = ["#2E86DE", "#E67E22", "#16A085", "#C0392B"];
|
||||||
|
foreach (var (aspect, index) in applicableAspects.Select((a, i) => (a, i)))
|
||||||
|
series.Add(new(aspect.Label, colors[index % colors.Length],
|
||||||
|
points.Where(p => p.AspectValues.ContainsKey(aspect.Key)).Select(p => new ReportChartPoint(p.Date,
|
||||||
|
ParticipationRatingScale.Normalize(aspect.ValueType, p.AspectValues[aspect.Key], aspect.MaxPoints))).ToList()));
|
||||||
|
var box = DrawingBoxLocator.Find(template, StudentReportTemplate.Participation)!.Value;
|
||||||
|
var drawing = ParticipationReportDrawing.Build(series, options.From, options.To, box.Width, box.MillimeterScale);
|
||||||
|
if (drawing.ContentHeight > box.Height)
|
||||||
|
throw new InvalidDataException("Der Mitarbeitsgraph benötigt eine höhere Zeichenbox in der Vorlage.");
|
||||||
|
values[StudentReportTemplate.Participation] = drawing;
|
||||||
|
}
|
||||||
|
if (options.IncludeCompetencies && Uses(StudentReportTemplate.Competencies))
|
||||||
|
{
|
||||||
|
var groupExams = exams.GetByGroup(group.Id).Where(e => Within(e.Date)).ToList();
|
||||||
|
var examIds = groupExams.Select(e => e.Id).ToHashSet();
|
||||||
|
var scores = competencies.Analyze(domains.GetAll(), [], groupExams,
|
||||||
|
results.GetByStudent(student.Id).Where(r => examIds.Contains(r.ExamId)).ToList(),
|
||||||
|
groupSessions, studentEntries, applicableAspects);
|
||||||
|
var lines = scores.Where(s => s.StudentScores.ContainsKey(student.Id)).Select(s =>
|
||||||
|
{
|
||||||
|
var score = s.StudentScores[student.Id];
|
||||||
|
return $"{s.Code} {s.Description}: {score.Percent.ToString("0", System.Globalization.CultureInfo.GetCultureInfo("de-DE"))} % ({score.EvidenceCount} Bewertungen)";
|
||||||
|
}).ToList();
|
||||||
|
Add(StudentReportTemplate.Competencies, "Kompetenzen", lines, "Keine Kompetenzbewertungen im gewählten Zeitraum.");
|
||||||
|
}
|
||||||
|
if (options.IncludeHomework && Uses(StudentReportTemplate.Homework))
|
||||||
|
Add(StudentReportTemplate.Homework, "Hausaufgaben", studentEntries.Where(e => HomeworkDisplay.Effective(e) is not null)
|
||||||
|
.OrderBy(e => bySession[e.SessionId].Date).Select(e =>
|
||||||
|
$"{bySession[e.SessionId].Date:dd.MM.yyyy}: {HomeworkDisplay.Label(HomeworkDisplay.Effective(e))}").ToList(),
|
||||||
|
"Keine Hausaufgabenkontrollen im gewählten Zeitraum.");
|
||||||
|
if (options.IncludeDocumentation && Uses(StudentReportTemplate.Documentation))
|
||||||
|
{
|
||||||
|
var lines = documentation.GetByStudent(student.Id)
|
||||||
|
.Where(d => !d.IsDeleted && !d.IsDraft && (options.IncludeConfidential || !d.IsConfidential)
|
||||||
|
&& d.GroupId == group.Id && Within(d.Date) && d.Concerns(student.Id))
|
||||||
|
.OrderBy(d => d.Date).Select(d =>
|
||||||
|
$"{d.Date:dd.MM.yyyy} · {DocumentationTypeDisplay.Label(d.Type)}: {d.Title}"
|
||||||
|
+ (d.IsConfidential ? " [Vertraulich]" : "") + "\n" + d.Content).ToList();
|
||||||
|
lines.AddRange(studentEntries.Where(e => !string.IsNullOrWhiteSpace(e.Note)).OrderBy(e => bySession[e.SessionId].Date)
|
||||||
|
.Select(e => $"{bySession[e.SessionId].Date:dd.MM.yyyy} · Unterrichtsnotiz: {e.Note}"));
|
||||||
|
Add(StudentReportTemplate.Documentation, "Klassenbucheinträge und Unterrichtsnotizen", lines,
|
||||||
|
"Keine freigegebenen Einträge mit Bezug zu dieser Lerngruppe im gewählten Zeitraum.");
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
|
||||||
|
bool Uses(string name) => DrawingBoxLocator.Find(template, name) is not null;
|
||||||
|
void Add(string name, string title, List<string> lines, string empty) =>
|
||||||
|
values[name] = GradeReportDrawingBuilder.Text(template, name, title, lines.Count > 0 ? lines : [empty]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
|
public enum StudentEvidenceKind { Absence, Lateness, Homework }
|
||||||
|
|
||||||
|
/// <summary>Ein einzelner Beleg hinter einer klassenübergreifenden Warnung (ein Fehltermin, eine
|
||||||
|
/// Verspätung, eine offene Hausaufgabe) — Code/Farbe bewusst identisch mit der Klassenlehrer-
|
||||||
|
/// Monatsansicht (ClassTeacherDetailsViewModel.BuildDayEvents: U/E/A/V/H), damit dasselbe Kürzel in
|
||||||
|
/// beiden Widgets dasselbe bedeutet.</summary>
|
||||||
|
public sealed record StudentEvidenceEvent(DateOnly Date, string GroupName, string Label, string Code,
|
||||||
|
string ColorHex, StudentEvidenceKind Kind)
|
||||||
|
{
|
||||||
|
private static readonly CultureInfo De = new("de-DE");
|
||||||
|
public string DateLabel => Date.ToString("ddd dd.MM.", De);
|
||||||
|
public string ListLine => $"{Date:dd.MM.yyyy} · {GroupName}: {Label}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Momentaufnahme aller Belege einer/eines Schüler*in im laufenden Schuljahr. Grundlage
|
||||||
|
/// sowohl für das Detail-Popup der Dashboard-Warnungen als auch für die Schnellbausteine/Vorlagen
|
||||||
|
/// beim Anlegen von Vorgängen und Dokumentation — beides soll exakt dieselben Zahlen zeigen, die
|
||||||
|
/// die Warnung ausgelöst haben.</summary>
|
||||||
|
public sealed record StudentWarningEvidence(
|
||||||
|
Guid StudentId, string StudentName, string StudentFirstName, string StudentNaturalName, string SchoolYear, DateOnly From, DateOnly To, DateOnly AsOf,
|
||||||
|
AttendanceBalance Balance,
|
||||||
|
IReadOnlyList<StudentEvidenceEvent> Absences,
|
||||||
|
IReadOnlyList<StudentEvidenceEvent> Lateness,
|
||||||
|
IReadOnlyList<StudentEvidenceEvent> MissingHomework)
|
||||||
|
{
|
||||||
|
public int SignificantlyLateCount => Lateness.Count(e => e.Code == "V!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sammelt die Belege hinter den drei klassenübergreifenden Dashboard-Warnungen (Fehlzeiten,
|
||||||
|
/// Hausaufgaben-Rückstand, Verspätungen) für eine/n einzelne/n Schüler*in. Zählt bewusst nach
|
||||||
|
/// denselben Regeln wie DashboardViewModel.LoadAttendanceWarnings/LoadMissingHomeworkWarnings/
|
||||||
|
/// LoadLatenessWarnings (Schuljahreszeitraum, AttendanceBalanceService, HomeworkDisplay.CountsAsMissing,
|
||||||
|
/// Late/SignificantlyLate) — eine abweichende Zahl im Popup als in der Warnzeile wäre verwirrend.
|
||||||
|
/// Keine eigene Persistenz, rein lesend.
|
||||||
|
/// </summary>
|
||||||
|
public class StudentWarningEvidenceService
|
||||||
|
{
|
||||||
|
private readonly IStudentRepository _students;
|
||||||
|
private readonly IParticipationSessionRepository _sessions;
|
||||||
|
private readonly IParticipationRepository _entries;
|
||||||
|
private readonly IGroupRepository _groups;
|
||||||
|
private readonly SchoolYearService _sy;
|
||||||
|
private readonly AttendanceBalanceService _attendanceBalance;
|
||||||
|
private readonly Func<DateTime> _now;
|
||||||
|
|
||||||
|
public StudentWarningEvidenceService(IStudentRepository students, IParticipationSessionRepository sessions,
|
||||||
|
IParticipationRepository entries, IGroupRepository groups, SchoolYearService sy,
|
||||||
|
AttendanceBalanceService attendanceBalance, Func<DateTime>? now = null)
|
||||||
|
{
|
||||||
|
_students = students;
|
||||||
|
_sessions = sessions;
|
||||||
|
_entries = entries;
|
||||||
|
_groups = groups;
|
||||||
|
_sy = sy;
|
||||||
|
_attendanceBalance = attendanceBalance;
|
||||||
|
_now = now ?? (() => DateTime.Now);
|
||||||
|
}
|
||||||
|
|
||||||
|
public StudentWarningEvidence Build(Guid studentId)
|
||||||
|
{
|
||||||
|
var schoolYear = _sy.CurrentSchoolYear();
|
||||||
|
var from = _sy.SchoolYearStart(schoolYear);
|
||||||
|
var to = _sy.SchoolYearEnd(schoolYear);
|
||||||
|
var sessions = _sessions.GetAll().ToDictionary(s => s.Id);
|
||||||
|
var groupNames = _groups.GetAll(includeInactive: true).ToDictionary(g => g.Id, g => g.Name);
|
||||||
|
|
||||||
|
var dated = _entries.GetByStudent(studentId)
|
||||||
|
.Select(e => (Entry: e, Session: sessions.GetValueOrDefault(e.SessionId)))
|
||||||
|
.Where(x => x.Session is not null && x.Session.Date >= from && x.Session.Date <= to)
|
||||||
|
.Select(x => (x.Entry, x.Session!.Date, Group: groupNames.GetValueOrDefault(x.Session.GroupId, "")))
|
||||||
|
.OrderByDescending(x => x.Date).ThenBy(x => x.Group)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var balance = _attendanceBalance.Calculate(dated.Select(x => (x.Date, x.Entry.Attendance)), from, to);
|
||||||
|
|
||||||
|
var absences = new List<StudentEvidenceEvent>();
|
||||||
|
var lateness = new List<StudentEvidenceEvent>();
|
||||||
|
var homework = new List<StudentEvidenceEvent>();
|
||||||
|
foreach (var (entry, date, group) in dated)
|
||||||
|
{
|
||||||
|
if (AbsenceEvent(entry.Attendance, date, group) is { } absence) absences.Add(absence);
|
||||||
|
if (entry.Attendance is AttendanceStatus.Late or AttendanceStatus.SignificantlyLate)
|
||||||
|
lateness.Add(new StudentEvidenceEvent(date, group, AttendanceDisplay.Label(entry.Attendance),
|
||||||
|
entry.Attendance == AttendanceStatus.SignificantlyLate ? "V!" : "V", "#EF6C00",
|
||||||
|
StudentEvidenceKind.Lateness));
|
||||||
|
var hw = HomeworkDisplay.Effective(entry);
|
||||||
|
if (HomeworkDisplay.CountsAsMissing(hw))
|
||||||
|
homework.Add(new StudentEvidenceEvent(date, group, HomeworkDisplay.Label(hw), "H", "#6A1B9A",
|
||||||
|
StudentEvidenceKind.Homework));
|
||||||
|
}
|
||||||
|
|
||||||
|
var student = _students.GetById(studentId);
|
||||||
|
return new StudentWarningEvidence(studentId, student?.FullName ?? "", student?.FirstName ?? "",
|
||||||
|
student is null ? "" : $"{student.FirstName} {student.LastName}".Trim(), schoolYear, from, to, DateOnly.FromDateTime(_now()),
|
||||||
|
balance, absences, lateness, homework);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nur die Status, die AttendanceBalanceService in die Fehlquote einrechnet (entschuldigt,
|
||||||
|
/// unentschuldigt, Entschuldigung offen) — schulisch veranlasste Abwesenheit zählt dort nicht als
|
||||||
|
/// Fehlzeit und taucht deshalb auch hier nicht als Beleg auf.
|
||||||
|
private static StudentEvidenceEvent? AbsenceEvent(AttendanceStatus? status, DateOnly date, string group)
|
||||||
|
{
|
||||||
|
var (code, color) = status switch
|
||||||
|
{
|
||||||
|
AttendanceStatus.Unexcused or AttendanceStatus.Truant or AttendanceStatus.LeftDuringClass => ("U", "#C62828"),
|
||||||
|
AttendanceStatus.ExcusePending => ("A", "#1565C0"),
|
||||||
|
AttendanceStatus.Excused => ("E", "#2E7D32"),
|
||||||
|
_ => ("", ""),
|
||||||
|
};
|
||||||
|
return code == "" ? null
|
||||||
|
: new StudentEvidenceEvent(date, group, AttendanceDisplay.Label(status), code, color, StudentEvidenceKind.Absence);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
|
internal sealed class TeacherSettingsConfig
|
||||||
|
{
|
||||||
|
public string Abbreviation { get; set; } = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Angaben zur Lehrkraft, die auf Formularen erscheinen (bisher nur das Kürzel fürs
|
||||||
|
/// Klausur-Deckblatt) — aus der Konfiguration statt fest in der Vorlage, damit eine weitergegebene
|
||||||
|
/// Vorlage nicht das Kürzel ihres Erstellers trägt.</summary>
|
||||||
|
public sealed class TeacherSettingsService
|
||||||
|
{
|
||||||
|
private readonly string _configPath;
|
||||||
|
|
||||||
|
public TeacherSettingsService(string appDataPath) =>
|
||||||
|
_configPath = Path.Combine(appDataPath, "teachersettings.json");
|
||||||
|
|
||||||
|
public string LoadAbbreviation()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (File.Exists(_configPath))
|
||||||
|
return JsonSerializer.Deserialize<TeacherSettingsConfig>(File.ReadAllText(_configPath))
|
||||||
|
?.Abbreviation ?? "";
|
||||||
|
}
|
||||||
|
catch { /* beschädigte Konfiguration -> leer */ }
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SaveAbbreviation(string abbreviation)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(_configPath,
|
||||||
|
JsonSerializer.Serialize(new TeacherSettingsConfig { Abbreviation = abbreviation.Trim() }));
|
||||||
|
}
|
||||||
|
catch { /* Einstellung ist Komfort — Fehler beim Schreiben nicht an die UI durchreichen */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,6 +34,7 @@ public sealed class UntisReportCacheService(
|
|||||||
{
|
{
|
||||||
private static readonly TimeSpan HotWindowRefreshInterval = TimeSpan.FromHours(1);
|
private static readonly TimeSpan HotWindowRefreshInterval = TimeSpan.FromHours(1);
|
||||||
private const int HotWindowDays = 14;
|
private const int HotWindowDays = 14;
|
||||||
|
private const int AbsenceReportVersion = 2;
|
||||||
|
|
||||||
/// Roster hat anders als Fehlzeiten/Klassenbuch keine Historie (nur "aktueller Stand einer
|
/// Roster hat anders als Fehlzeiten/Klassenbuch keine Historie (nur "aktueller Stand einer
|
||||||
/// Klasse") - deshalb ohne heißes/kaltes Fenster, nur "gilt der letzte Abruf noch als frisch".
|
/// Klasse") - deshalb ohne heißes/kaltes Fenster, nur "gilt der letzte Abruf noch als frisch".
|
||||||
@@ -66,6 +67,10 @@ public sealed class UntisReportCacheService(
|
|||||||
DateOnly start, DateOnly end, bool forceRefresh = false, CancellationToken token = default)
|
DateOnly start, DateOnly end, bool forceRefresh = false, CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var state = fetchState.Get(className, UntisCacheKind.Absences);
|
var state = fetchState.Get(className, UntisCacheKind.Absences);
|
||||||
|
// Ältere Berichte haben Tage mit einzelnen Fehlstunden als Fehltage geliefert.
|
||||||
|
// Auch die dauerhaft gecachte Historie muss mit der Trennung neu geladen werden.
|
||||||
|
if (state is not null && state.AbsenceReportVersion != AbsenceReportVersion)
|
||||||
|
state = new UntisCacheFetchState { Id = state.Id, ClassName = className, Kind = UntisCacheKind.Absences };
|
||||||
var plan = Plan(state, start, end, Today(), forceRefresh, DateTime.UtcNow);
|
var plan = Plan(state, start, end, Today(), forceRefresh, DateTime.UtcNow);
|
||||||
|
|
||||||
if (plan.RefreshHotWindow)
|
if (plan.RefreshHotWindow)
|
||||||
@@ -76,7 +81,7 @@ public sealed class UntisReportCacheService(
|
|||||||
if (plan.FetchColdRange)
|
if (plan.FetchColdRange)
|
||||||
{
|
{
|
||||||
var older = await untis.GetClassAbsencesAsync(className, plan.ColdRangeStart, plan.ColdRangeEnd, token);
|
var older = await untis.GetClassAbsencesAsync(className, plan.ColdRangeStart, plan.ColdRangeEnd, token);
|
||||||
absenceCache.InsertRange(older.Select(ToEntry));
|
absenceCache.ReplaceRange(className, Int(plan.ColdRangeStart), Int(plan.ColdRangeEnd), older.Select(ToEntry));
|
||||||
}
|
}
|
||||||
if (plan.RefreshHotWindow || plan.FetchColdRange)
|
if (plan.RefreshHotWindow || plan.FetchColdRange)
|
||||||
fetchState.Save(NextState(state, className, UntisCacheKind.Absences, plan));
|
fetchState.Save(NextState(state, className, UntisCacheKind.Absences, plan));
|
||||||
@@ -137,6 +142,7 @@ public sealed class UntisReportCacheService(
|
|||||||
Id = previous?.Id ?? Guid.NewGuid(),
|
Id = previous?.Id ?? Guid.NewGuid(),
|
||||||
ClassName = className,
|
ClassName = className,
|
||||||
Kind = kind,
|
Kind = kind,
|
||||||
|
AbsenceReportVersion = kind == UntisCacheKind.Absences ? AbsenceReportVersion : 0,
|
||||||
HotWindowFetchedAt = plan.RefreshHotWindow ? DateTime.UtcNow : previous?.HotWindowFetchedAt,
|
HotWindowFetchedAt = plan.RefreshHotWindow ? DateTime.UtcNow : previous?.HotWindowFetchedAt,
|
||||||
ColdCoverageStartDate = plan.ResultingColdCoverageStartDate,
|
ColdCoverageStartDate = plan.ResultingColdCoverageStartDate,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -114,6 +114,10 @@ public sealed class WebUntisIntegrationService(HttpClient http, WebUntisSettings
|
|||||||
x.ActivityType, x.Info, x.LessonText, x.SubstitutionText, x.StudentGroup,
|
x.ActivityType, x.Info, x.LessonText, x.SubstitutionText, x.StudentGroup,
|
||||||
Entities(x.Classes), Entities(x.Teachers), Entities(x.Subjects), Entities(x.Rooms))).ToList(), token);
|
Entities(x.Classes), Entities(x.Teachers), Entities(x.Subjects), Entities(x.Rooms))).ToList(), token);
|
||||||
|
|
||||||
|
public Task<IReadOnlyDictionary<int, int>> GetWeeklyLessonIdsAsync(int teacherId, DateOnly date,
|
||||||
|
CancellationToken token = default) => ExecuteAsync(
|
||||||
|
client => client.GetWeeklyLessonIdsAsync(teacherId, date, token), token);
|
||||||
|
|
||||||
public Task<IReadOnlyList<UntisTimetableGridEntryDto>> GetOwnTimetableGridAsync(DateOnly start, DateOnly end,
|
public Task<IReadOnlyList<UntisTimetableGridEntryDto>> GetOwnTimetableGridAsync(DateOnly start, DateOnly end,
|
||||||
CancellationToken token = default) => ExecuteAsync(async client =>
|
CancellationToken token = default) => ExecuteAsync(async client =>
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,17 +1,24 @@
|
|||||||
using CommunityToolkit.Mvvm.ComponentModel;
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||||||
|
using CommunityToolkit.Mvvm.Input;
|
||||||
using System.Windows.Input;
|
using System.Windows.Input;
|
||||||
|
|
||||||
namespace LehrerApp.Desktop.ViewModels;
|
namespace LehrerApp.Desktop.ViewModels;
|
||||||
|
|
||||||
/// <summary>Die sieben Dashboard-Kacheln, die tatsächlich "wo muss ich reagieren" beantworten
|
/// <summary>Die neun Dashboard-Kacheln, die tatsächlich "wo muss ich reagieren" beantworten
|
||||||
/// (siehe <see cref="DashboardViewModel.AttentionCount"/>), zusammengefasst zu einer Karte mit
|
/// (siehe <see cref="DashboardViewModel.AttentionCount"/>), zusammengefasst zu einer Karte mit
|
||||||
/// Filter-Chips statt sieben eigenen Sichtbarkeits-Schaltern. Reihenfolge hier ist die Reihenfolge
|
/// Filter-Chips statt eigenen Sichtbarkeits-Schaltern je Art. Reihenfolge hier ist die Reihenfolge
|
||||||
/// der Gruppen in der zusammengefassten Ansicht (siehe DashboardViewModel.RebuildAttention) — sie
|
/// der Gruppen in der zusammengefassten Ansicht (siehe DashboardViewModel.RebuildAttention) — sie
|
||||||
/// übernimmt bewusst die frühere Sortierung aus DashboardSettingsService.DefaultCardOrder, damit
|
/// übernimmt bewusst die frühere Sortierung aus DashboardSettingsService.DefaultCardOrder, damit
|
||||||
/// sich nichts, was Nutzer bereits kennen, unvorhersehbar umsortiert.
|
/// sich nichts, was Nutzer bereits kennen, unvorhersehbar umsortiert.
|
||||||
/// "Klausurwochen" (examload) bleibt bewusst außen vor: die Einträge dort sind Wochen-Aggregate,
|
/// "Klausurwochen" (examload) bleibt bewusst außen vor: die Einträge dort sind Wochen-Aggregate,
|
||||||
/// keine Einzelvorgänge, die sich abhaken oder anklicken lassen — sie passen nicht ins Item-Modell.</summary>
|
/// keine Einzelvorgänge, die sich abhaken oder anklicken lassen — sie passen nicht ins Item-Modell.
|
||||||
public enum AttentionKind { MissingTeachingTime, Excuse, Correction, Unplanned, Alert, Attendance, SupportPlan }
|
/// MissingHomework/Lateness (Hausaufgaben-/Verspätungs-Warnung) ergänzen Attendance um dieselbe
|
||||||
|
/// klassenübergreifende Logik — alle drei navigieren über OnNavigateToStudentCase direkt auf den
|
||||||
|
/// "Vorgänge"-Tab des Schülerdetails statt auf dessen Standard-Tab (siehe DashboardViewModel).</summary>
|
||||||
|
public enum AttentionKind
|
||||||
|
{
|
||||||
|
MissingTeachingTime, Excuse, Correction, Unplanned, Alert, Attendance, MissingHomework, Lateness, SupportPlan,
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Eine Inline-Aktion auf einem Handlungsbedarf-Eintrag (z.B. "Entschuldigt"/"Unentschuldigt",
|
/// <summary>Eine Inline-Aktion auf einem Handlungsbedarf-Eintrag (z.B. "Entschuldigt"/"Unentschuldigt",
|
||||||
/// "Erfassen"). Verwendet ICommand statt Action, damit die bereits vorhandenen generierten
|
/// "Erfassen"). Verwendet ICommand statt Action, damit die bereits vorhandenen generierten
|
||||||
@@ -40,16 +47,34 @@ public sealed class AttentionItem
|
|||||||
/// <summary>Text unter der ProgressBar, z.B. "3 von 5 Arbeiten bewertet". Nur bei Korrekturen gesetzt.</summary>
|
/// <summary>Text unter der ProgressBar, z.B. "3 von 5 Arbeiten bewertet". Nur bei Korrekturen gesetzt.</summary>
|
||||||
public string ProgressLabel { get; }
|
public string ProgressLabel { get; }
|
||||||
/// <summary>Färbt TrailingText wie die frühere Fehlzeiten-Warnung (fest "Foreground=Red") ein —
|
/// <summary>Färbt TrailingText wie die frühere Fehlzeiten-Warnung (fest "Foreground=Red") ein —
|
||||||
/// nur bei Attendance gesetzt, weil ein AttentionItem dieser Art per Konstruktion nur entsteht,
|
/// bei Attendance/MissingHomework/Lateness gesetzt, weil ein AttentionItem dieser Arten per
|
||||||
/// wenn die Fehlzeitenquote den Schwellenwert bereits überschreitet.</summary>
|
/// Konstruktion nur entsteht, wenn der jeweilige Schwellenwert bereits überschritten ist.</summary>
|
||||||
public bool IsWarningTrailing { get; }
|
public bool IsWarningTrailing { get; }
|
||||||
|
/// <summary>Nur bei Attendance/MissingHomework/Lateness gesetzt: ein offener Vorgang mit
|
||||||
|
/// passendem Tag wurde kürzlich bearbeitet, oder die Warnung wurde manuell zurückgestellt (siehe
|
||||||
|
/// DashboardViewModel.SnoozeWarningAsync) — beides zeitlich befristet, damit eine ausbleibende
|
||||||
|
/// Besserung nach Ablauf der Frist wieder auffällt statt dauerhaft entschärft zu bleiben. Steuert
|
||||||
|
/// die Optik (grau statt rot), die Einordnung in die eingeklappte "Zurückgestellt"-Gruppe und
|
||||||
|
/// das Herausnehmen aus DashboardViewModel.AttentionCount; der Schwellenwert-
|
||||||
|
/// Vergleich selbst bleibt unverändert, die Warnung verschwindet also ganz, sobald sich die
|
||||||
|
/// zugrunde liegende Zahl tatsächlich bessert.</summary>
|
||||||
|
public bool IsDefused { get; }
|
||||||
public IReadOnlyList<AttentionAction> Actions { get; }
|
public IReadOnlyList<AttentionAction> Actions { get; }
|
||||||
public Action? Navigate { get; }
|
public Action? Navigate { get; }
|
||||||
|
/// <summary>Nur bei Attendance/MissingHomework/Lateness gesetzt: Inhalt des "Details"-Popups
|
||||||
|
/// (Nutzer-Feedback: im Dashboard-Eintrag mehr erfahren). Erst beim ersten Zugriff erzeugt — die
|
||||||
|
/// Flyout-Bindung greift darauf erst beim Öffnen zu, damit das Dashboard nicht für jede Warnzeile
|
||||||
|
/// vorab alle Belege sammelt.</summary>
|
||||||
|
public StudentWarningDetailViewModel? Detail => _detail ??= _detailFactory?.Invoke();
|
||||||
|
private readonly Func<StudentWarningDetailViewModel>? _detailFactory;
|
||||||
|
private StudentWarningDetailViewModel? _detail;
|
||||||
|
|
||||||
public AttentionItem(AttentionKind kind, string title, string subtitle = "", string trailingText = "",
|
public AttentionItem(AttentionKind kind, string title, string subtitle = "", string trailingText = "",
|
||||||
string dateDisplay = "", bool isOverdue = false, AlertSeverity? severity = null,
|
string dateDisplay = "", bool isOverdue = false, AlertSeverity? severity = null,
|
||||||
int progressPercent = 0, string progressLabel = "", bool hasProgress = false,
|
int progressPercent = 0, string progressLabel = "", bool hasProgress = false,
|
||||||
bool isWarningTrailing = false, IReadOnlyList<AttentionAction>? actions = null, Action? navigate = null)
|
bool isWarningTrailing = false, bool isDefused = false,
|
||||||
|
IReadOnlyList<AttentionAction>? actions = null, Action? navigate = null,
|
||||||
|
Func<StudentWarningDetailViewModel>? detailFactory = null)
|
||||||
{
|
{
|
||||||
Kind = kind;
|
Kind = kind;
|
||||||
Title = title;
|
Title = title;
|
||||||
@@ -62,30 +87,58 @@ public sealed class AttentionItem
|
|||||||
ProgressLabel = progressLabel;
|
ProgressLabel = progressLabel;
|
||||||
HasProgress = hasProgress;
|
HasProgress = hasProgress;
|
||||||
IsWarningTrailing = isWarningTrailing;
|
IsWarningTrailing = isWarningTrailing;
|
||||||
|
IsDefused = isDefused;
|
||||||
Actions = actions ?? [];
|
Actions = actions ?? [];
|
||||||
Navigate = navigate;
|
Navigate = navigate;
|
||||||
|
_detailFactory = detailFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool HasSubtitle => !string.IsNullOrWhiteSpace(Subtitle);
|
public bool HasSubtitle => !string.IsNullOrWhiteSpace(Subtitle);
|
||||||
public bool HasTrailingText => !string.IsNullOrWhiteSpace(TrailingText);
|
public bool HasTrailingText => !string.IsNullOrWhiteSpace(TrailingText);
|
||||||
public bool HasDate => !string.IsNullOrWhiteSpace(DateDisplay);
|
public bool HasDate => !string.IsNullOrWhiteSpace(DateDisplay);
|
||||||
public bool HasActions => Actions.Count > 0;
|
public bool HasActions => Actions.Count > 0;
|
||||||
|
public bool HasDetail => _detailFactory is not null;
|
||||||
|
public bool HasFooter => HasActions || HasDetail;
|
||||||
public bool HasSeverity => Severity is not null;
|
public bool HasSeverity => Severity is not null;
|
||||||
public bool IsHighSeverity => Severity == AlertSeverity.High;
|
public bool IsHighSeverity => Severity == AlertSeverity.High;
|
||||||
public bool IsMediumSeverity => Severity == AlertSeverity.Medium;
|
public bool IsMediumSeverity => Severity == AlertSeverity.Medium;
|
||||||
public bool IsAttendanceWarning => Kind == AttentionKind.Attendance;
|
/// Färbt den linken Severity-Balken wie die frühere Fehlzeiten-Warnung ein — für alle drei
|
||||||
|
/// klassenübergreifenden Warnarten (Fehlzeiten/Hausaufgaben/Verspätungen), die per Konstruktion
|
||||||
|
/// nur entstehen, wenn ihr jeweiliger Schwellenwert bereits überschritten ist.
|
||||||
|
public bool IsCrossClassWarning => Kind is AttentionKind.Attendance or AttentionKind.MissingHomework or AttentionKind.Lateness;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Eine Kind-Gruppe innerhalb der zusammengefassten Handlungsbedarf-Liste. Items behalten
|
/// <summary>Eine Kind-Gruppe innerhalb der zusammengefassten Handlungsbedarf-Liste. Items behalten
|
||||||
/// die Sortierung, die ihre jeweilige LoadXxx-Methode schon immer produziert hat (z.B. Fehlzeiten
|
/// die Sortierung, die ihre jeweilige LoadXxx-Methode schon immer produziert hat (z.B. Fehlzeiten
|
||||||
/// nach Quote absteigend, Korrekturen nach Datum) — ein zweites, generisches "Importance"-Sortieren
|
/// nach Quote absteigend, Korrekturen nach Datum) — ein zweites, generisches "Importance"-Sortieren
|
||||||
/// quer über alle Arten würde diese bewusst gewählten Reihenfolgen wieder zerstören.</summary>
|
/// quer über alle Arten würde diese bewusst gewählten Reihenfolgen wieder zerstören.
|
||||||
public sealed class AttentionGroup(AttentionKind kind, string header, IReadOnlyList<AttentionItem> items)
|
/// Sonderfall IsDeferred: die "Zurückgestellt"-Gruppe am Ende sammelt entschärfte Warnungen aller
|
||||||
|
/// drei klassenübergreifenden Arten (Kind deshalb null) und ist ein-/ausklappbar.</summary>
|
||||||
|
public sealed partial class AttentionGroup : ObservableObject
|
||||||
{
|
{
|
||||||
public AttentionKind Kind { get; } = kind;
|
public AttentionKind? Kind { get; }
|
||||||
public string Header { get; } = header;
|
public string Header { get; }
|
||||||
public IReadOnlyList<AttentionItem> Items { get; } = items;
|
public IReadOnlyList<AttentionItem> Items { get; }
|
||||||
public int Count => Items.Count;
|
public int Count => Items.Count;
|
||||||
|
public bool IsDeferred { get; }
|
||||||
|
[ObservableProperty] [NotifyPropertyChangedFor(nameof(ExpandGlyph))] private bool _isExpanded;
|
||||||
|
public string ExpandGlyph => IsExpanded ? "▾" : "▸";
|
||||||
|
private readonly Action<bool>? _onExpandedChanged;
|
||||||
|
|
||||||
|
public AttentionGroup(AttentionKind? kind, string header, IReadOnlyList<AttentionItem> items,
|
||||||
|
bool isDeferred = false, bool isExpanded = true, Action<bool>? onExpandedChanged = null)
|
||||||
|
{
|
||||||
|
Kind = kind;
|
||||||
|
Header = header;
|
||||||
|
Items = items;
|
||||||
|
IsDeferred = isDeferred;
|
||||||
|
_isExpanded = isExpanded;
|
||||||
|
_onExpandedChanged = onExpandedChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnIsExpandedChanged(bool value) => _onExpandedChanged?.Invoke(value);
|
||||||
|
|
||||||
|
[RelayCommand] private void ToggleExpanded() => IsExpanded = !IsExpanded;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Ein Filter-Chip für eine Handlungsbedarf-Art in der zusammengefassten Karte — ersetzt
|
/// <summary>Ein Filter-Chip für eine Handlungsbedarf-Art in der zusammengefassten Karte — ersetzt
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
using System.Text;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebUntis-Stand einer/eines Schüler*in der eigenen Klasse für Schnellbausteine und Vorlagen im
|
||||||
|
/// Klassenlehrer-"Vorgänge"-Tab — Gegenstück zu StudentWarningEvidence im Schülerdetail. Dort zählen
|
||||||
|
/// nur die lokal erfassten Mitarbeits-Einträge der eigenen Stunden; die Klassenleitung braucht
|
||||||
|
/// dagegen die Fehlzeiten über alle Fächer und die Klassenbucheinträge der Kolleg*innen, die
|
||||||
|
/// WebUntis ohnehin liefert (und <see cref="Services.UntisReportCacheService"/> für das laufende
|
||||||
|
/// Schuljahr bereits gecacht hat). Rein aus schon geladenen Zeilen berechnet, testbar ohne Untis.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="NaturalName">"Vorname Nachname" aus dem lokalen Schülerdatensatz — der Untis-Anzeigename
|
||||||
|
/// hat je nach Schule eine andere Reihenfolge und taugt nicht für eine Briefanrede.</param>
|
||||||
|
public sealed record ClassTeacherStudentFacts(StudentOption Student, string NaturalName, string SchoolYear, DateOnly AsOf,
|
||||||
|
IReadOnlyList<ClassAbsenceDaySummaryRow> AbsenceDays, IReadOnlyList<ClassAbsenceDaySummaryRow> LateDays,
|
||||||
|
IReadOnlyList<ClassTeacherClassRegisterRow> RegisterEntries)
|
||||||
|
{
|
||||||
|
public const int MaxListed = 15;
|
||||||
|
|
||||||
|
public int AbsentPeriods => AbsenceDays.Sum(d => d.TotalAbsentPeriods);
|
||||||
|
public int FullDays => AbsenceDays.Count(d => d.CountsAsFullDay);
|
||||||
|
public int UnexcusedDays => AbsenceDays.Count(d => d.CountsAsFullDay && d.IsUnexcused);
|
||||||
|
public int PartialAbsentPeriods => AbsenceDays.Where(d => !d.CountsAsFullDay).Sum(d => d.TotalAbsentPeriods);
|
||||||
|
public int UnexcusedPartialPeriods => AbsenceDays
|
||||||
|
.Where(d => !d.CountsAsFullDay && d.IsUnexcused).Sum(d => d.TotalAbsentPeriods);
|
||||||
|
public int NegativeRegisterCount => RegisterEntries.Count(r => r.IsDangerStatus);
|
||||||
|
public IReadOnlyList<ClassTeacherClassRegisterRow> HomeworkEntries => RegisterEntries
|
||||||
|
.Where(r => ($"{r.CategoryName} {r.Text}").Contains("Hausauf", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||||
|
|
||||||
|
private string Stand => $"WebUntis-Stand {AsOf:dd.MM.yyyy}";
|
||||||
|
|
||||||
|
public string AbsenceShort =>
|
||||||
|
$"{FullDayLabel(FullDays)} und " +
|
||||||
|
$"{PartialAbsentPeriods} weitere Fehlstunde{(PartialAbsentPeriods == 1 ? "" : "n")} " +
|
||||||
|
$"an {AbsenceDays.Count} Tag{(AbsenceDays.Count == 1 ? "" : "en")} im Schuljahr {SchoolYear} " +
|
||||||
|
$"(unentschuldigt: {FullDayCountLabel(UnexcusedDays)}, " +
|
||||||
|
$"{UnexcusedPartialPeriods} Fehlstunde{(UnexcusedPartialPeriods == 1 ? "" : "n")})";
|
||||||
|
public string LatenessShort => $"{LateDays.Count} Verspätung{(LateDays.Count == 1 ? "" : "en")} im Schuljahr {SchoolYear}";
|
||||||
|
public string RegisterShort =>
|
||||||
|
$"{RegisterEntries.Count} Klassenbucheintr{(RegisterEntries.Count == 1 ? "ag" : "äge")} im Schuljahr {SchoolYear}, davon {NegativeRegisterCount} negativ";
|
||||||
|
public string HomeworkShort => $"{HomeworkEntries.Count} Klassenbucheintr{(HomeworkEntries.Count == 1 ? "ag" : "äge")} zu Hausaufgaben im Schuljahr {SchoolYear}";
|
||||||
|
|
||||||
|
public string AbsenceBlock => $"{Stand}: {AbsenceShort}.\n" + List("Fehlzeiten", AbsenceDays.Select(d =>
|
||||||
|
$"{d.DateLabel}: {d.KindLabel} · {d.FriendlyStatusLabel}" +
|
||||||
|
(string.IsNullOrWhiteSpace(d.DetailLabel) ? "" : $" · {d.DetailLabel}")).ToList());
|
||||||
|
public string LatenessBlock => $"{Stand}: {LatenessShort}.\n" + List("Termine", LateDays.Select(d =>
|
||||||
|
$"{d.DateLabel}: {d.KindLabel}").ToList());
|
||||||
|
public string RegisterBlock => $"{Stand}: {RegisterShort}.\n" + List("Einträge", RegisterEntries.Select(RegisterLine).ToList());
|
||||||
|
public string HomeworkBlock => $"{Stand}: {HomeworkShort}.\n" + List("Einträge", HomeworkEntries.Select(RegisterLine).ToList());
|
||||||
|
|
||||||
|
private static string RegisterLine(ClassTeacherClassRegisterRow r) =>
|
||||||
|
$"{r.DateLabel}" + (string.IsNullOrWhiteSpace(r.Subject) ? "" : $" · {r.Subject}") + ": " +
|
||||||
|
string.Join(" – ", new[] { r.CategoryName, r.Text }.Where(v => !string.IsNullOrWhiteSpace(v)));
|
||||||
|
|
||||||
|
private static string FullDayLabel(int count) =>
|
||||||
|
count == 1 ? "1 ganzer Fehltag" : $"{count} ganze Fehltage";
|
||||||
|
|
||||||
|
private static string FullDayCountLabel(int count) =>
|
||||||
|
count == 1 ? "1 ganzer Tag" : $"{count} ganze Tage";
|
||||||
|
|
||||||
|
private static string List(string header, IReadOnlyList<string> lines)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder($"{header}:");
|
||||||
|
foreach (var line in lines.Take(MaxListed)) sb.Append("\n- ").Append(line);
|
||||||
|
if (lines.Count > MaxListed) sb.Append($"\n- … und {lines.Count - MaxListed} weitere");
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nur Bausteine mit Inhalt. Mit <paramref name="withName"/> (mehrere Beteiligte ausgewählt)
|
||||||
|
/// tragen Label und Text den Namen, sonst wäre unklar, wessen Zahlen gerade eingefügt werden.
|
||||||
|
public IEnumerable<VorgangQuickBlock> QuickBlocks(bool withName)
|
||||||
|
{
|
||||||
|
string L(string label) => withName ? $"{label} · {Student.Name}" : label;
|
||||||
|
string T(string text) => withName ? $"{Student.Name} – {text}" : text;
|
||||||
|
if (AbsenceDays.Count > 0) yield return new(L("Fehlzeiten"), T(AbsenceBlock));
|
||||||
|
if (LateDays.Count > 0) yield return new(L("Verspätungen"), T(LatenessBlock));
|
||||||
|
if (HomeworkEntries.Count > 0) yield return new(L("Hausaufgaben (Klassenbuch)"), T(HomeworkBlock));
|
||||||
|
if (RegisterEntries.Count > 0) yield return new(L("Klassenbucheinträge"), T(RegisterBlock));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Anlass-Zeilen passend zu den Vorgangs-Tags; ohne passendes Tag (z.B. "Konflikte") dienen die
|
||||||
|
/// negativen Klassenbucheinträge als Anlass, sofern vorhanden.
|
||||||
|
public VorgangTemplateContext TemplateContext(Vorgang vorgang)
|
||||||
|
{
|
||||||
|
var lines = new List<string>();
|
||||||
|
foreach (var tag in vorgang.Tags.Select(t => t.ToLowerInvariant()).Distinct())
|
||||||
|
{
|
||||||
|
if (tag == "absentismus" && AbsenceDays.Count > 0) lines.Add(AbsenceShort);
|
||||||
|
if (tag == "verspätungen" && LateDays.Count > 0) lines.Add(LatenessShort);
|
||||||
|
if (tag == "hausaufgaben" && HomeworkEntries.Count > 0) lines.Add(HomeworkShort);
|
||||||
|
}
|
||||||
|
if (lines.Count == 0 && NegativeRegisterCount > 0) lines.Add(RegisterShort);
|
||||||
|
|
||||||
|
return new VorgangTemplateContext(Student.Id, NaturalName, AsOf, lines,
|
||||||
|
new Dictionary<string, VorgangSnapshot>
|
||||||
|
{
|
||||||
|
[VorgangDocumentationTemplates.UntisAbsenceStatus] = new($"Fehlzeiten-Stand (WebUntis) {AsOf:dd.MM.yyyy}", AbsenceBlock),
|
||||||
|
[VorgangDocumentationTemplates.LatenessStatus] = new($"Verspätungs-Stand (WebUntis) {AsOf:dd.MM.yyyy}", LatenessBlock),
|
||||||
|
[VorgangDocumentationTemplates.ClassRegisterStatus] = new($"Klassenbuch-Stand {AsOf:dd.MM.yyyy}", RegisterBlock),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ClassTeacherStudentFacts Build(StudentOption student, string naturalName, string schoolYear, DateOnly asOf,
|
||||||
|
IReadOnlyList<ClassAbsenceDaySummaryRow> classAbsenceDays, IReadOnlyList<ClassTeacherClassRegisterRow> classRegister)
|
||||||
|
{
|
||||||
|
var own = classAbsenceDays.Where(a => UntisNameMatching.NamesMatch(a.StudentName, student.Name))
|
||||||
|
.OrderByDescending(a => a.Date).ToList();
|
||||||
|
var register = classRegister.Where(r => UntisNameMatching.NamesMatch(r.StudentName, student.Name))
|
||||||
|
.OrderByDescending(r => r.Date).ToList();
|
||||||
|
return new ClassTeacherStudentFacts(student, naturalName, schoolYear, asOf,
|
||||||
|
own.Where(a => !a.IsLate).ToList(), own.Where(a => a.IsLate).ToList(), register);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ using CommunityToolkit.Mvvm.ComponentModel;
|
|||||||
using CommunityToolkit.Mvvm.Input;
|
using CommunityToolkit.Mvvm.Input;
|
||||||
using LehrerApp.Core.Interfaces;
|
using LehrerApp.Core.Interfaces;
|
||||||
using LehrerApp.Core.Models;
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
using LehrerApp.Desktop.Services;
|
using LehrerApp.Desktop.Services;
|
||||||
using LehrerApp.Desktop.ViewModels.Students;
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
|
||||||
@@ -26,6 +27,10 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
|||||||
|
|
||||||
private string _className = "";
|
private string _className = "";
|
||||||
private List<StudentOption> _rosterStudentOptions = [];
|
private List<StudentOption> _rosterStudentOptions = [];
|
||||||
|
// WebUntis-Stand je Schüler*in für Schnellbausteine/Vorlagen (ClassTeacherStudentFacts) — erst
|
||||||
|
// beim Öffnen eines Dialogs geladen (EnsureFactsAsync), nicht bei jedem Neuladen der Liste.
|
||||||
|
private Dictionary<Guid, ClassTeacherStudentFacts> _facts = [];
|
||||||
|
private Guid? _documentationDraftId;
|
||||||
|
|
||||||
public ObservableCollection<VorgangItem> Cases { get; } = [];
|
public ObservableCollection<VorgangItem> Cases { get; } = [];
|
||||||
|
|
||||||
@@ -37,7 +42,8 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
|||||||
|
|
||||||
public Func<List<StudentOption>, Vorgang?, Task<Vorgang?>>? OnEditVorgang { get; set; }
|
public Func<List<StudentOption>, Vorgang?, Task<Vorgang?>>? OnEditVorgang { get; set; }
|
||||||
public Func<VorgangItem, Task<bool>>? OnConfirmDeleteVorgang { get; set; }
|
public Func<VorgangItem, Task<bool>>? OnConfirmDeleteVorgang { get; set; }
|
||||||
public Func<Guid, List<StudentOption>, Documentation?, Task<Documentation?>>? OnEditDocumentation { get; set; }
|
/// Parameter: Hauptperson, Bezug-Auswahl, Kandidaten für "Betrifft außerdem", bestehender Eintrag.
|
||||||
|
public Func<Guid, List<StudentOption>, List<StudentOption>, Documentation?, Task<Documentation?>>? OnEditDocumentation { get; set; }
|
||||||
|
|
||||||
public ClassTeacherCasesViewModel(IVorgangRepository vorgaenge, IDocumentationRepository documentation,
|
public ClassTeacherCasesViewModel(IVorgangRepository vorgaenge, IDocumentationRepository documentation,
|
||||||
IStudentRepository students, UntisReportCacheService cache)
|
IStudentRepository students, UntisReportCacheService cache)
|
||||||
@@ -98,13 +104,16 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
|||||||
.Where(n => n != "");
|
.Where(n => n != "");
|
||||||
var item = new VorgangItem(vorgang, string.Join(", ", names), LinkDocumentation,
|
var item = new VorgangItem(vorgang, string.Join(", ", names), LinkDocumentation,
|
||||||
UnlinkDocumentation, RemoveClassRegisterEntry, EditDocumentation)
|
UnlinkDocumentation, RemoveClassRegisterEntry, EditDocumentation)
|
||||||
{ IsRevealed = revealedIds.Contains(vorgang.Id) };
|
{
|
||||||
|
IsRevealed = revealedIds.Contains(vorgang.Id),
|
||||||
|
OnCreateFromTemplate = CreateDocumentationFromTemplate,
|
||||||
|
};
|
||||||
|
|
||||||
var linkedIds = vorgang.DocumentationIds.ToHashSet();
|
var linkedIds = vorgang.DocumentationIds.ToHashSet();
|
||||||
foreach (var doc in allDocs.Where(d => linkedIds.Contains(d.Id)))
|
foreach (var doc in allDocs.Where(d => linkedIds.Contains(d.Id)))
|
||||||
item.LinkedDocumentation.Add(new DocumentationItem(doc, nameById.GetValueOrDefault(doc.StudentId, "")));
|
item.LinkedDocumentation.Add(new DocumentationItem(doc, InvolvedNames(doc, nameById)));
|
||||||
foreach (var doc in FilterAvailableDocumentation(allDocs, vorgang))
|
foreach (var doc in FilterAvailableDocumentation(allDocs, vorgang))
|
||||||
item.AvailableDocumentation.Add(new DocumentationItem(doc, nameById.GetValueOrDefault(doc.StudentId, "")));
|
item.AvailableDocumentation.Add(new DocumentationItem(doc, InvolvedNames(doc, nameById)));
|
||||||
foreach (var entry in vorgang.ClassRegisterEntries.OrderByDescending(e => e.Date))
|
foreach (var entry in vorgang.ClassRegisterEntries.OrderByDescending(e => e.Date))
|
||||||
item.ClassRegisterRows.Add(new VorgangClassRegisterEntryRow(entry));
|
item.ClassRegisterRows.Add(new VorgangClassRegisterEntryRow(entry));
|
||||||
|
|
||||||
@@ -117,10 +126,102 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
|||||||
|
|
||||||
private void NotifyState() => OnPropertyChanged(nameof(HasCases));
|
private void NotifyState() => OnPropertyChanged(nameof(HasCases));
|
||||||
|
|
||||||
|
private static string InvolvedNames(Documentation doc, Dictionary<Guid, string> nameById) =>
|
||||||
|
string.Join(", ", doc.InvolvedStudentIds().Select(id => nameById.GetValueOrDefault(id, "")).Where(n => n != ""));
|
||||||
|
|
||||||
|
private List<StudentOption> VorgangStudentOptions(Vorgang vorgang) =>
|
||||||
|
_rosterStudentOptions.Where(s => vorgang.StudentIds.Contains(s.Id)).ToList();
|
||||||
|
|
||||||
|
/// "Betrifft außerdem"-Kandidaten beim Bearbeiten eines Eintrags: die Beteiligten aller angezeigten
|
||||||
|
/// Vorgänge, in denen der Eintrag verknüpft oder verknüpfbar ist, plus die schon Beteiligten —
|
||||||
|
/// bewusst nicht der ganze Klassen-Roster, damit die Liste kurz bleibt.
|
||||||
|
private List<StudentOption> CoStudentOptionsFor(Documentation doc)
|
||||||
|
{
|
||||||
|
var ids = Cases.Select(c => c.Model)
|
||||||
|
.Where(v => v.DocumentationIds.Contains(doc.Id) || v.StudentIds.Any(doc.Concerns))
|
||||||
|
.SelectMany(v => v.StudentIds)
|
||||||
|
.Concat(doc.InvolvedStudentIds())
|
||||||
|
.ToHashSet();
|
||||||
|
return _rosterStudentOptions.Where(s => ids.Contains(s.Id)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lädt Fehlzeiten und Klassenbucheinträge des laufenden Schuljahres (aus dem Untis-Cache, der
|
||||||
|
/// kalte Bereich ist dort dauerhaft gespeichert) und leitet daraus den Stand je Schüler*in ab.
|
||||||
|
/// Scheitert der Abruf (offline, Sitzung abgelaufen), gibt es eben nur die Standardformulierungen
|
||||||
|
/// statt eines Fehlers — der Dialog selbst soll davon nicht abhängen.
|
||||||
|
private async Task EnsureFactsAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var sy = new SchoolYearService();
|
||||||
|
var schoolYear = sy.CurrentSchoolYear();
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var start = sy.SchoolYearStart(schoolYear);
|
||||||
|
var absencesTask = _cache.GetAbsencesAsync(_className, start, today);
|
||||||
|
var registerTask = _cache.GetClassRegisterEventsAsync(_className, start, today);
|
||||||
|
await Task.WhenAll(absencesTask, registerTask);
|
||||||
|
|
||||||
|
var absenceDays = ClassAbsenceDaySummaryRow.GroupByStudentAndDay(absencesTask.Result);
|
||||||
|
var register = registerTask.Result
|
||||||
|
.Select(e => (Entry: e, Valid: DateOnly.TryParseExact(e.Date.ToString(), "yyyyMMdd", out var d), Date: d))
|
||||||
|
.Where(x => x.Valid)
|
||||||
|
.Select(x => new ClassTeacherClassRegisterRow(x.Date, x.Entry.Subject, x.Entry.StudentName,
|
||||||
|
x.Entry.TeacherUsername, x.Entry.CategoryName, x.Entry.CategoryGroup, x.Entry.Text))
|
||||||
|
.ToList();
|
||||||
|
_facts = _rosterStudentOptions.ToDictionary(o => o.Id, o => ClassTeacherStudentFacts.Build(o,
|
||||||
|
NaturalName(o), schoolYear, today, absenceDays, register));
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// Bewusst still: ohne WebUntis fehlen nur die Zahlen-Bausteine, Standardformulierungen
|
||||||
|
// und Vorlagen (dann ohne Zahlen) bleiben nutzbar.
|
||||||
|
_facts = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string NaturalName(StudentOption option) =>
|
||||||
|
_students.GetById(option.Id) is { } s ? $"{s.FirstName} {s.LastName}".Trim() : option.Name;
|
||||||
|
|
||||||
|
/// Schnellbausteine für die aktuell im Dialog ausgewählten Schüler*innen — bei mehreren mit Namen.
|
||||||
|
public IReadOnlyList<VorgangQuickBlock> QuickBlocksFor(IReadOnlyList<Guid> studentIds) => studentIds
|
||||||
|
.Where(_facts.ContainsKey)
|
||||||
|
.SelectMany(id => _facts[id].QuickBlocks(withName: studentIds.Count > 1))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
public bool IsNewDocumentationDraft(Documentation doc) => doc.Id == _documentationDraftId;
|
||||||
|
|
||||||
|
/// Vorlagen beziehen sich auf die/den erste/n Beteiligte/n des Vorgangs (Dokumentation gehört immer
|
||||||
|
/// zu genau einer Person) — der Dialog bietet deshalb auch nur diese Person an, sonst passten die
|
||||||
|
/// eingesetzten Zahlen nicht mehr zur gewählten Person.
|
||||||
|
private async Task CreateDocumentationFromTemplate(VorgangItem item, string key)
|
||||||
|
{
|
||||||
|
if (OnEditDocumentation is null) return;
|
||||||
|
var option = _rosterStudentOptions.FirstOrDefault(o => item.Model.StudentIds.Contains(o.Id));
|
||||||
|
if (option is null) return;
|
||||||
|
await EnsureFactsAsync();
|
||||||
|
var context = _facts.TryGetValue(option.Id, out var facts)
|
||||||
|
? facts.TemplateContext(item.Model)
|
||||||
|
: new VorgangTemplateContext(option.Id, NaturalName(option), DateOnly.FromDateTime(DateTime.Today), [],
|
||||||
|
new Dictionary<string, VorgangSnapshot>());
|
||||||
|
var draft = VorgangDocumentationTemplates.Build(key, item.Model, context);
|
||||||
|
if (draft is null) return;
|
||||||
|
|
||||||
|
_documentationDraftId = draft.Id;
|
||||||
|
Documentation? result;
|
||||||
|
try { result = await OnEditDocumentation(option.Id, [option], VorgangStudentOptions(item.Model), draft); }
|
||||||
|
finally { _documentationDraftId = null; }
|
||||||
|
if (result is null) return;
|
||||||
|
_documentation.Save(result);
|
||||||
|
item.Model.DocumentationIds.Add(result.Id);
|
||||||
|
_vorgaenge.Save(item.Model);
|
||||||
|
await LoadInternal();
|
||||||
|
}
|
||||||
|
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
private async Task AddVorgang()
|
private async Task AddVorgang()
|
||||||
{
|
{
|
||||||
if (OnEditVorgang is null) return;
|
if (OnEditVorgang is null) return;
|
||||||
|
await EnsureFactsAsync();
|
||||||
var result = await OnEditVorgang(_rosterStudentOptions, null);
|
var result = await OnEditVorgang(_rosterStudentOptions, null);
|
||||||
if (result is null) return;
|
if (result is null) return;
|
||||||
_vorgaenge.Save(result);
|
_vorgaenge.Save(result);
|
||||||
@@ -131,6 +232,7 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
|||||||
private async Task EditVorgang(VorgangItem? item)
|
private async Task EditVorgang(VorgangItem? item)
|
||||||
{
|
{
|
||||||
if (item is null || OnEditVorgang is null) return;
|
if (item is null || OnEditVorgang is null) return;
|
||||||
|
await EnsureFactsAsync();
|
||||||
var result = await OnEditVorgang(_rosterStudentOptions, item.Model);
|
var result = await OnEditVorgang(_rosterStudentOptions, item.Model);
|
||||||
if (result is null) return;
|
if (result is null) return;
|
||||||
_vorgaenge.Save(result);
|
_vorgaenge.Save(result);
|
||||||
@@ -160,9 +262,9 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
|||||||
private async Task CreateAndLinkDocumentation(VorgangItem? item)
|
private async Task CreateAndLinkDocumentation(VorgangItem? item)
|
||||||
{
|
{
|
||||||
if (item is null || OnEditDocumentation is null) return;
|
if (item is null || OnEditDocumentation is null) return;
|
||||||
var studentOptions = _rosterStudentOptions.Where(s => item.Model.StudentIds.Contains(s.Id)).ToList();
|
var studentOptions = VorgangStudentOptions(item.Model);
|
||||||
var defaultStudentId = item.Model.StudentIds.FirstOrDefault();
|
var defaultStudentId = item.Model.StudentIds.FirstOrDefault();
|
||||||
var result = await OnEditDocumentation(defaultStudentId, studentOptions, null);
|
var result = await OnEditDocumentation(defaultStudentId, studentOptions, studentOptions, null);
|
||||||
if (result is null) return;
|
if (result is null) return;
|
||||||
_documentation.Save(result);
|
_documentation.Save(result);
|
||||||
item.Model.DocumentationIds.Add(result.Id);
|
item.Model.DocumentationIds.Add(result.Id);
|
||||||
@@ -177,19 +279,20 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
|||||||
private async Task EditDocumentation(DocumentationItem doc)
|
private async Task EditDocumentation(DocumentationItem doc)
|
||||||
{
|
{
|
||||||
if (OnEditDocumentation is null) return;
|
if (OnEditDocumentation is null) return;
|
||||||
var result = await OnEditDocumentation(doc.Model.StudentId, _rosterStudentOptions, doc.Model);
|
var result = await OnEditDocumentation(doc.Model.StudentId, _rosterStudentOptions,
|
||||||
|
CoStudentOptionsFor(doc.Model), doc.Model);
|
||||||
if (result is null) return;
|
if (result is null) return;
|
||||||
_documentation.Save(result);
|
_documentation.Save(result);
|
||||||
await LoadInternal();
|
await LoadInternal();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dokumentation der Vorgangs-Schüler*innen, die noch nicht mit diesem Vorgang verknüpft ist —
|
/// Dokumentation der Vorgangs-Schüler*innen (als Haupt- oder weitere Beteiligte), die noch nicht
|
||||||
/// reine, ohne Repository-Zugriff testbare Filterlogik (gleiches Muster wie
|
/// mit diesem Vorgang verknüpft ist — reine, ohne Repository-Zugriff testbare Filterlogik
|
||||||
/// <see cref="ClassTeacherRosterRow.Build"/>).
|
/// (gleiches Muster wie <see cref="ClassTeacherRosterRow.Build"/>).
|
||||||
public static List<Documentation> FilterAvailableDocumentation(IReadOnlyList<Documentation> allDocs, Vorgang vorgang)
|
public static List<Documentation> FilterAvailableDocumentation(IReadOnlyList<Documentation> allDocs, Vorgang vorgang)
|
||||||
{
|
{
|
||||||
var linkedIds = vorgang.DocumentationIds.ToHashSet();
|
var linkedIds = vorgang.DocumentationIds.ToHashSet();
|
||||||
return allDocs.Where(d => vorgang.StudentIds.Contains(d.StudentId) && !linkedIds.Contains(d.Id)).ToList();
|
return allDocs.Where(d => vorgang.StudentIds.Any(d.Concerns) && !linkedIds.Contains(d.Id)).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task LinkDocumentation(VorgangItem item, DocumentationItem doc)
|
private async Task LinkDocumentation(VorgangItem item, DocumentationItem doc)
|
||||||
|
|||||||
@@ -66,6 +66,22 @@ public sealed record ClassAbsenceDaySummaryRow(DateOnly Date, string StudentName
|
|||||||
IReadOnlyList<int> PeriodNumbers, IReadOnlyList<string> Statuses, IReadOnlyList<string> AbsenceReasons,
|
IReadOnlyList<int> PeriodNumbers, IReadOnlyList<string> Statuses, IReadOnlyList<string> AbsenceReasons,
|
||||||
string? Note, string? ExcuseNote, bool CountsAsFullDay)
|
string? Note, string? ExcuseNote, bool CountsAsFullDay)
|
||||||
{
|
{
|
||||||
|
public bool CountsAsFullDay { get; init; } = CountsAsFullDay && !HasEarlyDepartureReason(AbsenceReasons);
|
||||||
|
public bool IsEarlyDeparture => HasEarlyDepartureReason(AbsenceReasons);
|
||||||
|
|
||||||
|
private static bool HasEarlyDepartureReason(IEnumerable<string> reasons) => reasons.Any(reason =>
|
||||||
|
reason.Contains("vorzeitig", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
((reason.Contains("früh", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
reason.Contains("frueh", StringComparison.OrdinalIgnoreCase)) &&
|
||||||
|
(reason.Contains("geh", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
reason.Contains("gegang", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
reason.Contains("verlass", StringComparison.OrdinalIgnoreCase))));
|
||||||
|
|
||||||
|
/// Nur für die Gewichtung von stundenweisen Fehlzeiten im Auffälligkeitsscore. Zeugnis- und
|
||||||
|
/// Anzeigezahlen verwenden weiterhin die echten WebUntis-Felder CountsAsFullDay bzw.
|
||||||
|
/// TotalAbsentPeriods und rechnen keine Stunden künstlich in Fehltage um.
|
||||||
|
public const int TypicalPeriodsPerSchoolDayForScoring = 6;
|
||||||
|
|
||||||
public string DateLabel => Date.ToString("dd.MM.yyyy");
|
public string DateLabel => Date.ToString("dd.MM.yyyy");
|
||||||
public string StudentDisplayName
|
public string StudentDisplayName
|
||||||
{
|
{
|
||||||
@@ -79,11 +95,18 @@ public sealed record ClassAbsenceDaySummaryRow(DateOnly Date, string StudentName
|
|||||||
public string PeriodsLabel => string.Join(", ", PeriodNumbers.Order());
|
public string PeriodsLabel => string.Join(", ", PeriodNumbers.Order());
|
||||||
public string StatusLabel => string.Join(", ", Statuses);
|
public string StatusLabel => string.Join(", ", Statuses);
|
||||||
public string ReasonLabel => string.Join("; ", AbsenceReasons);
|
public string ReasonLabel => string.Join("; ", AbsenceReasons);
|
||||||
public bool IsLate => TotalAbsentPeriods == 0 || AbsenceReasons.Any(r =>
|
public bool IsLate => !IsEarlyDeparture && (TotalAbsentPeriods == 0 || AbsenceReasons.Any(r =>
|
||||||
r.Contains("verspät", StringComparison.OrdinalIgnoreCase));
|
r.Contains("verspät", StringComparison.OrdinalIgnoreCase)));
|
||||||
public bool IsUnexcused => Statuses.Any(s =>
|
public bool IsUnexcused => Statuses.Any(s =>
|
||||||
s.Contains("nicht entsch", StringComparison.OrdinalIgnoreCase));
|
s.Contains("nicht entsch", StringComparison.OrdinalIgnoreCase));
|
||||||
public string KindLabel => IsLate ? $"{TotalAbsentMinutes} Min. verspätet" :
|
public bool IsPartialAbsence => !CountsAsFullDay && (!IsLate || IsUnexcused);
|
||||||
|
public double AbsenceDayEquivalentForScoring => IsLate && !IsUnexcused ? 0d : CountsAsFullDay ? 1d :
|
||||||
|
Math.Min(1d, (TotalAbsentPeriods > 0
|
||||||
|
? TotalAbsentPeriods
|
||||||
|
: TotalAbsentMinutes / 45d) / TypicalPeriodsPerSchoolDayForScoring);
|
||||||
|
public string KindLabel => IsEarlyDeparture
|
||||||
|
? $"Früher gegangen · {(TotalAbsentPeriods > 0 ? $"{TotalAbsentPeriods} Fehlstunde{(TotalAbsentPeriods == 1 ? "" : "n")}" : $"{TotalAbsentMinutes} Fehlminuten")}" :
|
||||||
|
IsLate ? $"{TotalAbsentMinutes} Min. verspätet" :
|
||||||
CountsAsFullDay ? "Ganzer Fehltag" : $"{TotalAbsentPeriods} Fehlstunde{(TotalAbsentPeriods == 1 ? "" : "n")}";
|
CountsAsFullDay ? "Ganzer Fehltag" : $"{TotalAbsentPeriods} Fehlstunde{(TotalAbsentPeriods == 1 ? "" : "n")}";
|
||||||
public string FriendlyStatusLabel => IsUnexcused ? "Unentschuldigt" :
|
public string FriendlyStatusLabel => IsUnexcused ? "Unentschuldigt" :
|
||||||
Statuses.Any(s => s.Contains("entsch", StringComparison.OrdinalIgnoreCase)) ? "Entschuldigt" : StatusLabel;
|
Statuses.Any(s => s.Contains("entsch", StringComparison.OrdinalIgnoreCase)) ? "Entschuldigt" : StatusLabel;
|
||||||
@@ -400,6 +423,13 @@ public partial class ClassTeacherDetailsViewModel : ObservableObject
|
|||||||
: absence.FriendlyStatusLabel.Contains("Entschuldigt", StringComparison.OrdinalIgnoreCase)
|
: absence.FriendlyStatusLabel.Contains("Entschuldigt", StringComparison.OrdinalIgnoreCase)
|
||||||
? ("E", "Entschuldigt gefehlt", "#2E7D32", ClassTeacherCalendarEventKind.Excused)
|
? ("E", "Entschuldigt gefehlt", "#2E7D32", ClassTeacherCalendarEventKind.Excused)
|
||||||
: ("A", "Abwesend", "#1565C0", ClassTeacherCalendarEventKind.Absent);
|
: ("A", "Abwesend", "#1565C0", ClassTeacherCalendarEventKind.Absent);
|
||||||
|
// Umfang und Entschuldigungsstatus sind unabhängig: Rot kann auch zwei
|
||||||
|
// unentschuldigte Fehlstunden bedeuten, nicht zwingend einen ganzen Fehltag.
|
||||||
|
if (absence.IsPartialAbsence && !absence.IsLate)
|
||||||
|
code = absence.IsEarlyDeparture ? "G" : "T";
|
||||||
|
else if (absence.IsLate)
|
||||||
|
code = "V";
|
||||||
|
label = $"{absence.KindLabel} · {absence.FriendlyStatusLabel}";
|
||||||
events.Add(new ClassTeacherCalendarEvent(absence.StudentDisplayName, code, label, color, kind));
|
events.Add(new ClassTeacherCalendarEvent(absence.StudentDisplayName, code, label, color, kind));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -454,7 +484,7 @@ public partial class ClassTeacherDetailsViewModel : ObservableObject
|
|||||||
var matchedIds = rosterMatches.Select(m => m.StudentId).ToHashSet();
|
var matchedIds = rosterMatches.Select(m => m.StudentId).ToHashSet();
|
||||||
return all
|
return all
|
||||||
.Where(d => !d.IsDeleted &&
|
.Where(d => !d.IsDeleted &&
|
||||||
(matchedIds.Contains(d.StudentId) || IsUnassignedClassDocumentation(d)) &&
|
(d.InvolvedStudentIds().Any(matchedIds.Contains) || IsUnassignedClassDocumentation(d)) &&
|
||||||
d.Date >= start && d.Date <= end)
|
d.Date >= start && d.Date <= end)
|
||||||
.Where(d => MatchesOwnDocStudentFilter(d, rosterMatches, studentFilter))
|
.Where(d => MatchesOwnDocStudentFilter(d, rosterMatches, studentFilter))
|
||||||
.OrderByDescending(d => d.IsDraft).ThenByDescending(d => d.Date)
|
.OrderByDescending(d => d.IsDraft).ThenByDescending(d => d.Date)
|
||||||
@@ -467,8 +497,10 @@ public partial class ClassTeacherDetailsViewModel : ObservableObject
|
|||||||
if (string.IsNullOrWhiteSpace(studentFilter)) return true;
|
if (string.IsNullOrWhiteSpace(studentFilter)) return true;
|
||||||
if (IsUnassignedClassDocumentation(d))
|
if (IsUnassignedClassDocumentation(d))
|
||||||
return d.Participants.Any(p => NameContainsSearchTerm(p, studentFilter));
|
return d.Participants.Any(p => NameContainsSearchTerm(p, studentFilter));
|
||||||
var name = rosterMatches.FirstOrDefault(m => m.StudentId == d.StudentId).DisplayName;
|
// Gemeinsame Einträge (weitere Beteiligte) passen, sobald eine der beteiligten Personen passt.
|
||||||
return name is not null && NameContainsSearchTerm(name, studentFilter);
|
return d.InvolvedStudentIds()
|
||||||
|
.Select(id => rosterMatches.FirstOrDefault(m => m.StudentId == id).DisplayName)
|
||||||
|
.Any(name => name is not null && NameContainsSearchTerm(name, studentFilter));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool IsUnassignedClassDocumentation(Documentation d) =>
|
private static bool IsUnassignedClassDocumentation(Documentation d) =>
|
||||||
@@ -485,8 +517,13 @@ public partial class ClassTeacherDetailsViewModel : ObservableObject
|
|||||||
IReadOnlyList<(Guid StudentId, string DisplayName)> rosterMatches)
|
IReadOnlyList<(Guid StudentId, string DisplayName)> rosterMatches)
|
||||||
{
|
{
|
||||||
if (d.StudentId != Guid.Empty)
|
if (d.StudentId != Guid.Empty)
|
||||||
return rosterMatches.FirstOrDefault(m => m.StudentId == d.StudentId).DisplayName
|
{
|
||||||
?? "Unbekannter Schülerbezug";
|
var names = d.InvolvedStudentIds()
|
||||||
|
.Select(id => rosterMatches.FirstOrDefault(m => m.StudentId == id).DisplayName)
|
||||||
|
.Where(n => n is not null)
|
||||||
|
.ToList();
|
||||||
|
return names.Count > 0 ? string.Join(", ", names) : "Unbekannter Schülerbezug";
|
||||||
|
}
|
||||||
return d.Participants.Count > 0
|
return d.Participants.Count > 0
|
||||||
? $"Ohne festen Bezug · {string.Join(", ", d.Participants)}"
|
? $"Ohne festen Bezug · {string.Join(", ", d.Participants)}"
|
||||||
: "Ohne Schülerbezug";
|
: "Ohne Schülerbezug";
|
||||||
|
|||||||
@@ -50,11 +50,7 @@ public sealed record ClassTeacherRosterRow(string StudentName, int? ExternKey, b
|
|||||||
{
|
{
|
||||||
if (TodayAbsence is null)
|
if (TodayAbsence is null)
|
||||||
return HasRecentClassRegisterEntry ? "Neuer Klassenbucheintrag" : "Keine gemeldete Fehlzeit";
|
return HasRecentClassRegisterEntry ? "Neuer Klassenbucheintrag" : "Keine gemeldete Fehlzeit";
|
||||||
var core = IsLate
|
var core = TodayAbsence.KindLabel;
|
||||||
? $"{TodayAbsence.TotalAbsentMinutes} Min. verspätet"
|
|
||||||
: TodayAbsence.CountsAsFullDay
|
|
||||||
? "Ganzer Fehltag"
|
|
||||||
: $"{TodayAbsence.TotalAbsentPeriods} Fehlstunde{(TodayAbsence.TotalAbsentPeriods == 1 ? "" : "n")}";
|
|
||||||
return IsUnexcused ? $"{core} · Unentschuldigt" : core;
|
return IsUnexcused ? $"{core} · Unentschuldigt" : core;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,21 +77,22 @@ public sealed record ClassTeacherRosterRow(string StudentName, int? ExternKey, b
|
|||||||
/// Kumulierte Fehlzeiten seit Schuljahresbeginn (Nutzer-Feedback: der Heute-Snapshot allein
|
/// Kumulierte Fehlzeiten seit Schuljahresbeginn (Nutzer-Feedback: der Heute-Snapshot allein
|
||||||
/// sagt für Zeugnis/Attestpflicht wenig aus). <see cref="SchoolDaysElapsed"/> zählt Werktage
|
/// sagt für Zeugnis/Attestpflicht wenig aus). <see cref="SchoolDaysElapsed"/> zählt Werktage
|
||||||
/// abzüglich der über WebUntis geladenen Ferien (<see cref="ClassTeacherOverviewViewModel.CountSchoolWeekdays"/>).
|
/// abzüglich der über WebUntis geladenen Ferien (<see cref="ClassTeacherOverviewViewModel.CountSchoolWeekdays"/>).
|
||||||
/// Zählt bewusst NUR echte Fehltage (unentschuldigt oder entschuldigt abwesend), keine reinen
|
/// Zählt bewusst NUR von WebUntis als ganze Fehltage gekennzeichnete Tage. Stundenweises
|
||||||
/// Verspätungstage mehr — Nutzer-Feedback: die Quote behandelte "10× 5 Min. verspätet" bisher
|
/// Fehlen bleibt davon getrennt in <see cref="YearAbsencePeriodCount"/> — auch wenn es
|
||||||
/// exakt wie "10× ganztägig unentschuldigt gefehlt", obwohl beides für die eigene Reaktion
|
/// unentschuldigt ist. Reine Verspätung landet separat in <see cref="YearLateDayCount"/>.
|
||||||
/// (Elterngespräch vs. Achselzucken) grundverschieden ist. Reine Verspätung landet stattdessen
|
|
||||||
/// separat in <see cref="YearLateDayCount"/> (gleiche Kategorisierung wie schon länger im
|
|
||||||
/// Wochentrend, siehe <see cref="ClassTeacherOverviewViewModel.BuildTrend"/>: Unentschuldigt vor
|
|
||||||
/// Verspätet vor Entschuldigt, überschneidungsfrei).
|
|
||||||
public int YearAbsenceDayCount { get; init; }
|
public int YearAbsenceDayCount { get; init; }
|
||||||
public int YearUnexcusedDayCount { get; init; }
|
public int YearUnexcusedDayCount { get; init; }
|
||||||
|
/// Fehlstunden aus nicht ganztägigen Fehlzeiten. Ganze Fehltage werden nicht zusätzlich noch
|
||||||
|
/// einmal als ihre enthaltenen Unterrichtsstunden gezählt.
|
||||||
|
public int YearAbsencePeriodCount { get; init; }
|
||||||
|
public int YearUnexcusedPeriodCount { get; init; }
|
||||||
|
public int YearExcusedPeriodCount { get; init; }
|
||||||
/// Tage, die WebUntis als Verspätung führt (ohne Unentschuldigt-Status) — zählen bewusst nicht
|
/// Tage, die WebUntis als Verspätung führt (ohne Unentschuldigt-Status) — zählen bewusst nicht
|
||||||
/// in <see cref="YearAbsenceDayCount"/>/<see cref="YearAbsenceRatePercent"/>, tragen aber mit
|
/// in <see cref="YearAbsenceDayCount"/>/<see cref="YearAbsenceRatePercent"/>, tragen aber mit
|
||||||
/// reduziertem Gewicht zu <see cref="PatternScore"/> bei.
|
/// reduziertem Gewicht zu <see cref="PatternScore"/> bei.
|
||||||
public int YearLateDayCount { get; init; }
|
public int YearLateDayCount { get; init; }
|
||||||
/// Entschuldigt abwesende Tage (weder unentschuldigt noch nur verspätet) — Kehrwert von
|
/// Entschuldigte ganze Fehltage — Gegenstück zu <see cref="YearUnexcusedDayCount"/> innerhalb
|
||||||
/// <see cref="YearUnexcusedDayCount"/> innerhalb von <see cref="YearAbsenceDayCount"/>.
|
/// von <see cref="YearAbsenceDayCount"/>. Stunden stehen getrennt in den Period-Eigenschaften.
|
||||||
public int YearExcusedDayCount { get; init; }
|
public int YearExcusedDayCount { get; init; }
|
||||||
/// Klassenbucheinträge anderer Lehrkräfte über das ganze bisherige Schuljahr mit
|
/// Klassenbucheinträge anderer Lehrkräfte über das ganze bisherige Schuljahr mit
|
||||||
/// <c>CategoryGroup</c> "Negativ" (Nutzer-Feedback: sollen ebenfalls ins Auffälligkeitsbild
|
/// <c>CategoryGroup</c> "Negativ" (Nutzer-Feedback: sollen ebenfalls ins Auffälligkeitsbild
|
||||||
@@ -121,23 +118,33 @@ public sealed record ClassTeacherRosterRow(string StudentName, int? ExternKey, b
|
|||||||
/// die Korrektur passiert also am Startpunkt, nicht an abgezogenen Tagen mittendrin.
|
/// die Korrektur passiert also am Startpunkt, nicht an abgezogenen Tagen mittendrin.
|
||||||
public DateOnly TermStart { get; init; }
|
public DateOnly TermStart { get; init; }
|
||||||
public bool HasYearSummary => SchoolDaysElapsed > 0 &&
|
public bool HasYearSummary => SchoolDaysElapsed > 0 &&
|
||||||
(YearAbsenceDayCount > 0 || YearLateDayCount > 0 || YearNegativeClassRegisterCount > 0);
|
(YearAbsenceDayCount > 0 || YearAbsencePeriodCount > 0 || YearLateDayCount > 0 ||
|
||||||
|
YearNegativeClassRegisterCount > 0);
|
||||||
public int YearAbsenceRatePercent =>
|
public int YearAbsenceRatePercent =>
|
||||||
SchoolDaysElapsed <= 0 ? 0 : (int)Math.Round(100d * YearAbsenceDayCount / SchoolDaysElapsed);
|
SchoolDaysElapsed <= 0 ? 0 : (int)Math.Round(100d * YearAbsenceDayCount / SchoolDaysElapsed);
|
||||||
public string YearSummaryLabel => !HasYearSummary ? "" :
|
public string YearSummaryLabel => !HasYearSummary ? "" :
|
||||||
YearAbsenceDayCount > 0 ? $"{YearAbsenceRatePercent} % Fehlzeit seit Schuljahresbeginn"
|
YearAbsenceDayCount > 0 ? $"{YearAbsenceRatePercent} % ganze Fehltage" +
|
||||||
|
(YearAbsencePeriodCount > 0 ? $" · {PeriodLabel(YearAbsencePeriodCount)}" : "")
|
||||||
|
: YearAbsencePeriodCount > 0 ? $"{PeriodLabel(YearAbsencePeriodCount)} seit Schuljahresbeginn"
|
||||||
: YearLateDayCount > 0 ? $"{YearLateDayCount}× verspätet, keine Fehltage seit Schuljahresbeginn"
|
: YearLateDayCount > 0 ? $"{YearLateDayCount}× verspätet, keine Fehltage seit Schuljahresbeginn"
|
||||||
: $"{YearNegativeClassRegisterCount} negative Klassenbucheinträge seit Schuljahresbeginn";
|
: $"{YearNegativeClassRegisterCount} negative Klassenbucheinträge seit Schuljahresbeginn";
|
||||||
public string? YearSummaryTooltip => !HasYearSummary ? null :
|
public string? YearSummaryTooltip => !HasYearSummary ? null :
|
||||||
(YearAbsenceDayCount > 0
|
(YearAbsenceDayCount > 0
|
||||||
? $"{YearAbsenceDayCount} von {SchoolDaysElapsed} Schultagen seit {TermStart:dd.MM.} mit Fehlzeit" +
|
? $"{YearAbsenceDayCount} von {SchoolDaysElapsed} Schultagen seit {TermStart:dd.MM.} als ganzer Fehltag" +
|
||||||
(YearUnexcusedDayCount > 0 ? $" · {YearUnexcusedDayCount} unentschuldigt" : "")
|
(YearUnexcusedDayCount > 0 ? $" · davon {YearUnexcusedDayCount} unentschuldigt" : "")
|
||||||
: $"Keine Fehltage seit {TermStart:dd.MM.}") +
|
: $"Keine ganzen Fehltage seit {TermStart:dd.MM.}") +
|
||||||
|
(YearAbsencePeriodCount > 0
|
||||||
|
? $" · {PeriodLabel(YearAbsencePeriodCount)}" +
|
||||||
|
(YearUnexcusedPeriodCount > 0 ? $" ({YearUnexcusedPeriodCount} unentschuldigt)" : "")
|
||||||
|
: "") +
|
||||||
(YearLateDayCount > 0 ? $" · {YearLateDayCount} Tage verspätet (zählt nicht zur Quote)" : "") +
|
(YearLateDayCount > 0 ? $" · {YearLateDayCount} Tage verspätet (zählt nicht zur Quote)" : "") +
|
||||||
(YearNegativeClassRegisterCount > 0 ? $" · {YearNegativeClassRegisterCount} negative Klassenbucheinträge" : "") +
|
(YearNegativeClassRegisterCount > 0 ? $" · {YearNegativeClassRegisterCount} negative Klassenbucheinträge" : "") +
|
||||||
(HasSuspensionEntry ? " · Suspendierung vermerkt" : "") +
|
(HasSuspensionEntry ? " · Suspendierung vermerkt" : "") +
|
||||||
(HolidayWeekdaysExcluded > 0 ? $" · {HolidayWeekdaysExcluded} Ferientage abgezogen" : "");
|
(HolidayWeekdaysExcluded > 0 ? $" · {HolidayWeekdaysExcluded} Ferientage abgezogen" : "");
|
||||||
|
|
||||||
|
private static string PeriodLabel(int count) =>
|
||||||
|
$"{count} Fehlstunde{(count == 1 ? "" : "n")}";
|
||||||
|
|
||||||
private static readonly string[] ConcerningKeywords = ["hausaufgabe", "mitarbeit"];
|
private static readonly string[] ConcerningKeywords = ["hausaufgabe", "mitarbeit"];
|
||||||
private static readonly string[] SuspensionKeywords = ["suspendier"];
|
private static readonly string[] SuspensionKeywords = ["suspendier"];
|
||||||
|
|
||||||
@@ -238,8 +245,10 @@ public sealed record ClassTeacherRosterRow(string StudentName, int? ExternKey, b
|
|||||||
var attendanceCutoff = cutoffFor(VorgangScoreDomain.Attendance);
|
var attendanceCutoff = cutoffFor(VorgangScoreDomain.Attendance);
|
||||||
var latenessCutoff = cutoffFor(VorgangScoreDomain.Lateness);
|
var latenessCutoff = cutoffFor(VorgangScoreDomain.Lateness);
|
||||||
var classbookCutoff = cutoffFor(VorgangScoreDomain.Classbook);
|
var classbookCutoff = cutoffFor(VorgangScoreDomain.Classbook);
|
||||||
var unexcused = yearEntries.Count(r => r.IsUnexcused && r.Date >= attendanceCutoff);
|
var unexcused = yearEntries.Where(r => r.IsUnexcused && r.Date >= attendanceCutoff)
|
||||||
var excused = yearEntries.Count(r => !r.IsUnexcused && !r.IsLate && r.Date >= attendanceCutoff);
|
.Sum(r => r.AbsenceDayEquivalentForScoring);
|
||||||
|
var excused = yearEntries.Where(r => !r.IsUnexcused && !r.IsLate && r.Date >= attendanceCutoff)
|
||||||
|
.Sum(r => r.AbsenceDayEquivalentForScoring);
|
||||||
var late = yearEntries.Count(r => !r.IsUnexcused && r.IsLate && r.Date >= latenessCutoff);
|
var late = yearEntries.Count(r => !r.IsUnexcused && r.IsLate && r.Date >= latenessCutoff);
|
||||||
var classRegister = yearRegisterEntries
|
var classRegister = yearRegisterEntries
|
||||||
.Where(e => TryDate(e.Date, out var d) && d >= classbookCutoff)
|
.Where(e => TryDate(e.Date, out var d) && d >= classbookCutoff)
|
||||||
@@ -314,13 +323,17 @@ public sealed record ClassTeacherRosterRow(string StudentName, int? ExternKey, b
|
|||||||
{
|
{
|
||||||
TodayAbsence = absence,
|
TodayAbsence = absence,
|
||||||
HasClassRegisterToday = registerEntries.Any(e => TryDate(e.Date, out var date) && date == referenceDate),
|
HasClassRegisterToday = registerEntries.Any(e => TryDate(e.Date, out var date) && date == referenceDate),
|
||||||
// Unentschuldigt vor Verspätet vor Entschuldigt, überschneidungsfrei — dieselbe
|
// Ganze Fehltage und stundenweises Fehlen bleiben getrennt. Insbesondere macht
|
||||||
// Kategorisierung wie im Wochentrend (BuildTrend). Nur Verspätung (nicht auch
|
// "unentschuldigt" aus einer einzelnen Fehlstunde keinen ganzen Fehltag.
|
||||||
// unentschuldigt) fällt bewusst aus YearAbsenceDayCount heraus, siehe dort.
|
YearAbsenceDayCount = yearEntries.Count(r => !r.IsLate && r.CountsAsFullDay),
|
||||||
YearAbsenceDayCount = yearEntries.Count(r => r.IsUnexcused || !r.IsLate),
|
YearUnexcusedDayCount = yearEntries.Count(r => !r.IsLate && r.CountsAsFullDay && r.IsUnexcused),
|
||||||
YearUnexcusedDayCount = yearEntries.Count(r => r.IsUnexcused),
|
YearAbsencePeriodCount = yearEntries.Where(r => r.IsPartialAbsence).Sum(r => r.TotalAbsentPeriods),
|
||||||
|
YearUnexcusedPeriodCount = yearEntries.Where(r => r.IsPartialAbsence && r.IsUnexcused)
|
||||||
|
.Sum(r => r.TotalAbsentPeriods),
|
||||||
|
YearExcusedPeriodCount = yearEntries.Where(r => r.IsPartialAbsence && !r.IsUnexcused)
|
||||||
|
.Sum(r => r.TotalAbsentPeriods),
|
||||||
YearLateDayCount = yearEntries.Count(r => !r.IsUnexcused && r.IsLate),
|
YearLateDayCount = yearEntries.Count(r => !r.IsUnexcused && r.IsLate),
|
||||||
YearExcusedDayCount = yearEntries.Count(r => !r.IsUnexcused && !r.IsLate),
|
YearExcusedDayCount = yearEntries.Count(r => !r.IsUnexcused && !r.IsLate && r.CountsAsFullDay),
|
||||||
YearNegativeClassRegisterCount = yearRegisterEntries.Count(IsNegativeClassRegisterEntry),
|
YearNegativeClassRegisterCount = yearRegisterEntries.Count(IsNegativeClassRegisterEntry),
|
||||||
HasSuspensionEntry = yearRegisterEntries.Any(e => MatchesAnyKeyword(e, SuspensionKeywords)),
|
HasSuspensionEntry = yearRegisterEntries.Any(e => MatchesAnyKeyword(e, SuspensionKeywords)),
|
||||||
ClassRegisterScoreComponent = yearRegisterEntries.Sum(e => ClassRegisterEntryWeight(e, effectiveWeights)),
|
ClassRegisterScoreComponent = yearRegisterEntries.Sum(e => ClassRegisterEntryWeight(e, effectiveWeights)),
|
||||||
@@ -1017,12 +1030,17 @@ public partial class ClassTeacherOverviewViewModel : ObservableObject
|
|||||||
var displayName = displayNamesByKey.GetValueOrDefault(group.Key) ?? rows[0].StudentDisplayName;
|
var displayName = displayNamesByKey.GetValueOrDefault(group.Key) ?? rows[0].StudentDisplayName;
|
||||||
var weekRows = rows.Where(row => row.Date >= sevenDayStart).ToList();
|
var weekRows = rows.Where(row => row.Date >= sevenDayStart).ToList();
|
||||||
var lateDaysWeek = weekRows.Count(row => row.IsLate);
|
var lateDaysWeek = weekRows.Count(row => row.IsLate);
|
||||||
var unexcusedDaysWeek = weekRows.Count(row => row.IsUnexcused && !row.IsLate);
|
var unexcusedDaysWeek = weekRows.Count(row => row.IsUnexcused && !row.IsLate && row.CountsAsFullDay);
|
||||||
|
var unexcusedPartialWeek = weekRows.Count(row => row.IsUnexcused && row.IsPartialAbsence);
|
||||||
var lateDaysYear = rows.Count(row => row.IsLate);
|
var lateDaysYear = rows.Count(row => row.IsLate);
|
||||||
|
|
||||||
if (unexcusedDaysWeek >= 2)
|
if (unexcusedDaysWeek >= 2)
|
||||||
notices.Add(new ClassTeacherPatternNotice(displayName,
|
notices.Add(new ClassTeacherPatternNotice(displayName,
|
||||||
$"{unexcusedDaysWeek} unentschuldigte Fehltage in 7 Tagen", ClassTeacherStatusKind.Danger));
|
$"{unexcusedDaysWeek} unentschuldigte Fehltage in 7 Tagen", ClassTeacherStatusKind.Danger));
|
||||||
|
else if (unexcusedPartialWeek >= 2)
|
||||||
|
notices.Add(new ClassTeacherPatternNotice(displayName,
|
||||||
|
$"{unexcusedPartialWeek} stundenweise unentschuldigte Fehlzeiten in 7 Tagen",
|
||||||
|
ClassTeacherStatusKind.Warning));
|
||||||
else if (lateDaysYear >= lateYearEscalationThreshold)
|
else if (lateDaysYear >= lateYearEscalationThreshold)
|
||||||
notices.Add(new ClassTeacherPatternNotice(displayName,
|
notices.Add(new ClassTeacherPatternNotice(displayName,
|
||||||
$"{lateDaysYear} Verspätungen seit Schuljahresbeginn – Elterngespräch oder Brief erwägen",
|
$"{lateDaysYear} Verspätungen seit Schuljahresbeginn – Elterngespräch oder Brief erwägen",
|
||||||
@@ -1157,7 +1175,8 @@ public partial class ClassTeacherOverviewViewModel : ObservableObject
|
|||||||
.Where(s => s is not null)
|
.Where(s => s is not null)
|
||||||
.Select(s => s!.Id)
|
.Select(s => s!.Id)
|
||||||
.ToHashSet();
|
.ToHashSet();
|
||||||
var docs = _documentation.GetAll().Where(d => !d.IsDeleted && matchedIds.Contains(d.StudentId)).ToList();
|
var docs = _documentation.GetAll()
|
||||||
|
.Where(d => !d.IsDeleted && d.InvolvedStudentIds().Any(matchedIds.Contains)).ToList();
|
||||||
OwnDocumentationFollowUpCount = docs.Count(d => d.IsDraft);
|
OwnDocumentationFollowUpCount = docs.Count(d => d.IsDraft);
|
||||||
OwnDocumentationCriticalCount = docs.Count(d =>
|
OwnDocumentationCriticalCount = docs.Count(d =>
|
||||||
d.Tags.Any(t => string.Equals(t, "Kritisch", StringComparison.OrdinalIgnoreCase)));
|
d.Tags.Any(t => string.Equals(t, "Kritisch", StringComparison.OrdinalIgnoreCase)));
|
||||||
|
|||||||
@@ -90,10 +90,26 @@ public partial class VorgangItem : ObservableObject
|
|||||||
_onUnlink = onUnlink;
|
_onUnlink = onUnlink;
|
||||||
_onRemoveClassRegisterEntry = onRemoveClassRegisterEntry;
|
_onRemoveClassRegisterEntry = onRemoveClassRegisterEntry;
|
||||||
_onEditDocumentation = onEditDocumentation;
|
_onEditDocumentation = onEditDocumentation;
|
||||||
|
LinkedDocumentation.CollectionChanged += (_, _) => OnPropertyChanged(nameof(HasLinkedDocumentation));
|
||||||
|
AvailableDocumentation.CollectionChanged += (_, _) => OnPropertyChanged(nameof(HasAvailableDocumentation));
|
||||||
|
ClassRegisterRows.CollectionChanged += (_, _) => OnPropertyChanged(nameof(HasClassRegisterRows));
|
||||||
}
|
}
|
||||||
|
|
||||||
[RelayCommand] private void Reveal() => IsRevealed = !IsRevealed;
|
[RelayCommand] private void Reveal() => IsRevealed = !IsRevealed;
|
||||||
|
|
||||||
|
/// Nutzer-Feedback: standardisierte Dokumentationseinträge statt alles von Hand — nur im
|
||||||
|
/// schülerbezogenen Vorgänge-Tab gesetzt (StudentVorgaengeViewModel), der Parameter ist ein
|
||||||
|
/// Schlüssel aus VorgangDocumentationTemplates. Eigener Command je Item statt $parent-Bindung,
|
||||||
|
/// weil die Auswahl in einem MenuFlyout-Popup liegt, das nicht im normalen visuellen Baum hängt.
|
||||||
|
public Func<VorgangItem, string, Task>? OnCreateFromTemplate { get; set; }
|
||||||
|
public bool HasDocumentationTemplates => OnCreateFromTemplate is not null;
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private async Task CreateFromTemplate(string? key)
|
||||||
|
{
|
||||||
|
if (key is not null && OnCreateFromTemplate is not null) await OnCreateFromTemplate(this, key);
|
||||||
|
}
|
||||||
|
|
||||||
/// Öffnet den vollen Dokumentations-Dialog zum Nachlesen/Bearbeiten, ohne den Vorgänge-Tab zu
|
/// Öffnet den vollen Dokumentations-Dialog zum Nachlesen/Bearbeiten, ohne den Vorgänge-Tab zu
|
||||||
/// verlassen (Nutzer-Feedback: bisher musste man dafür in den Schülerdatensatz wechseln).
|
/// verlassen (Nutzer-Feedback: bisher musste man dafür in den Schülerdatensatz wechseln).
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
@@ -138,14 +154,51 @@ public partial class VorgangDialogViewModel : ObservableObject
|
|||||||
[ObservableProperty] private string _titleError = "";
|
[ObservableProperty] private string _titleError = "";
|
||||||
[ObservableProperty] private string _studentsError = "";
|
[ObservableProperty] private string _studentsError = "";
|
||||||
|
|
||||||
public string DialogTitle => _editing is null ? "Vorgang anlegen" : "Vorgang bearbeiten";
|
private readonly bool _isNewDraft;
|
||||||
|
public string DialogTitle => _editing is null || _isNewDraft ? "Vorgang anlegen" : "Vorgang bearbeiten";
|
||||||
public Vorgang? Result { get; private set; }
|
public Vorgang? Result { get; private set; }
|
||||||
|
|
||||||
public VorgangDialogViewModel(List<StudentOption> rosterStudents, Vorgang? editing)
|
/// Per Klick in die Beschreibung einfügbare Textbausteine mit dem aktuellen Stand (Fehlquote,
|
||||||
|
/// Fehltermine, WebUntis-Fehlzeiten, …). Setzt sich aus festen Bausteinen (Schülerdetail) und —
|
||||||
|
/// im Klassenlehrer-Tab mit Mehrfachauswahl — aus Bausteinen je ausgewählter/m Schüler*in
|
||||||
|
/// zusammen, die bei jeder Änderung der Auswahl neu berechnet werden.
|
||||||
|
public ObservableCollection<VorgangQuickBlock> QuickBlocks { get; } = [];
|
||||||
|
public bool HasQuickBlocks => QuickBlocks.Count > 0;
|
||||||
|
/// Datumsgestempelte Standardformulierungen ("Klassenleitung informiert", …), siehe VorgangPhraseBlocks.
|
||||||
|
public IReadOnlyList<VorgangQuickBlock> PhraseBlocks { get; }
|
||||||
|
public bool HasPhraseBlocks => PhraseBlocks.Count > 0;
|
||||||
|
|
||||||
|
private readonly IReadOnlyList<VorgangQuickBlock> _fixedQuickBlocks;
|
||||||
|
private readonly Func<IReadOnlyList<Guid>, IReadOnlyList<VorgangQuickBlock>>? _studentQuickBlocks;
|
||||||
|
|
||||||
|
/// <param name="isNewDraft">editing ist ein noch nicht gespeicherter, vorbefüllter Entwurf (z.B.
|
||||||
|
/// aus einer Dashboard-Warnung) — Titel "anlegen" statt "bearbeiten".</param>
|
||||||
|
public VorgangDialogViewModel(List<StudentOption> rosterStudents, Vorgang? editing,
|
||||||
|
IReadOnlyList<VorgangQuickBlock>? quickBlocks = null, bool isNewDraft = false,
|
||||||
|
IReadOnlyList<VorgangQuickBlock>? phraseBlocks = null,
|
||||||
|
Func<IReadOnlyList<Guid>, IReadOnlyList<VorgangQuickBlock>>? studentQuickBlocks = null)
|
||||||
{
|
{
|
||||||
_editing = editing;
|
_editing = editing;
|
||||||
|
_isNewDraft = isNewDraft;
|
||||||
|
_fixedQuickBlocks = quickBlocks ?? [];
|
||||||
|
_studentQuickBlocks = studentQuickBlocks;
|
||||||
|
PhraseBlocks = phraseBlocks ?? [];
|
||||||
|
// Bei genau einem Kandidaten (z.B. der schülerbezogene Vorgänge-Tab im Schülerdetail) und
|
||||||
|
// einem neuen Vorgang ist ohnehin nur eine Auswahl möglich — Nutzer-Feedback: der sonst
|
||||||
|
// nötige Extra-Klick auf die einzige Checkbox ist unnötige Reibung.
|
||||||
StudentOptions = new ObservableCollection<VorgangStudentOption>(rosterStudents.Select(s =>
|
StudentOptions = new ObservableCollection<VorgangStudentOption>(rosterStudents.Select(s =>
|
||||||
new VorgangStudentOption(s.Id, s.Name) { IsSelected = editing?.StudentIds.Contains(s.Id) == true }));
|
new VorgangStudentOption(s.Id, s.Name)
|
||||||
|
{
|
||||||
|
IsSelected = editing?.StudentIds.Contains(s.Id) == true
|
||||||
|
|| (editing is null && rosterStudents.Count == 1),
|
||||||
|
}));
|
||||||
|
if (_studentQuickBlocks is not null)
|
||||||
|
foreach (var option in StudentOptions)
|
||||||
|
option.PropertyChanged += (_, e) =>
|
||||||
|
{
|
||||||
|
if (e.PropertyName == nameof(VorgangStudentOption.IsSelected)) RebuildQuickBlocks();
|
||||||
|
};
|
||||||
|
RebuildQuickBlocks();
|
||||||
if (editing is null) return;
|
if (editing is null) return;
|
||||||
|
|
||||||
Title = editing.Title;
|
Title = editing.Title;
|
||||||
@@ -164,6 +217,36 @@ public partial class VorgangDialogViewModel : ObservableObject
|
|||||||
|
|
||||||
[RelayCommand] private void RemoveTag(string? tag) { if (tag is not null) Tags.Remove(tag); }
|
[RelayCommand] private void RemoveTag(string? tag) { if (tag is not null) Tags.Remove(tag); }
|
||||||
|
|
||||||
|
/// Hängt den Baustein als eigenen Absatz an — nie überschreiben, damit bereits Getipptes bleibt.
|
||||||
|
[RelayCommand]
|
||||||
|
private void InsertQuickBlock(VorgangQuickBlock? block)
|
||||||
|
{
|
||||||
|
if (block is null) return;
|
||||||
|
var current = (Description ?? "").TrimEnd();
|
||||||
|
Description = current.Length == 0 ? block.Text : current + "\n\n" + block.Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Standardformulierungen sind Verlaufsnotizen — eine Zeile, kein eigener Absatz.
|
||||||
|
[RelayCommand]
|
||||||
|
private void InsertPhrase(VorgangQuickBlock? block)
|
||||||
|
{
|
||||||
|
if (block is null) return;
|
||||||
|
var current = (Description ?? "").TrimEnd();
|
||||||
|
Description = current.Length == 0 ? block.Text : current + "\n" + block.Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RebuildQuickBlocks()
|
||||||
|
{
|
||||||
|
QuickBlocks.Clear();
|
||||||
|
foreach (var block in _fixedQuickBlocks) QuickBlocks.Add(block);
|
||||||
|
if (_studentQuickBlocks is not null)
|
||||||
|
{
|
||||||
|
var selected = StudentOptions.Where(o => o.IsSelected).Select(o => o.StudentId).ToList();
|
||||||
|
foreach (var block in _studentQuickBlocks(selected)) QuickBlocks.Add(block);
|
||||||
|
}
|
||||||
|
OnPropertyChanged(nameof(HasQuickBlocks));
|
||||||
|
}
|
||||||
|
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
private void Save()
|
private void Save()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,6 +4,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.ViewModels.Groups;
|
||||||
using System.Collections.ObjectModel;
|
using System.Collections.ObjectModel;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
|
|
||||||
@@ -26,6 +27,8 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
private readonly IParticipationRepository _participationEntries;
|
private readonly IParticipationRepository _participationEntries;
|
||||||
private readonly IStudentRepository _students;
|
private readonly IStudentRepository _students;
|
||||||
private readonly IDocumentationRepository _documentation;
|
private readonly IDocumentationRepository _documentation;
|
||||||
|
private readonly IVorgangRepository _vorgaenge;
|
||||||
|
private readonly IDashboardWarningSnoozeRepository _warningSnoozes;
|
||||||
private readonly ITimetableSlotRepository _timetableSlots;
|
private readonly ITimetableSlotRepository _timetableSlots;
|
||||||
private readonly PeriodScheduleService _periodSchedule;
|
private readonly PeriodScheduleService _periodSchedule;
|
||||||
private readonly AttendanceBalanceService _attendanceBalance;
|
private readonly AttendanceBalanceService _attendanceBalance;
|
||||||
@@ -40,6 +43,7 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
private readonly SchoolWeatherService? _schoolWeather;
|
private readonly SchoolWeatherService? _schoolWeather;
|
||||||
private readonly UntisHubService _untisHub;
|
private readonly UntisHubService _untisHub;
|
||||||
private readonly WebUntisIntegrationService _webUntis;
|
private readonly WebUntisIntegrationService _webUntis;
|
||||||
|
private readonly StudentWarningEvidenceService _evidence;
|
||||||
private readonly Func<DateTime> _now;
|
private readonly Func<DateTime> _now;
|
||||||
|
|
||||||
private const int OpenExcuseMaxAgeDays = 21;
|
private const int OpenExcuseMaxAgeDays = 21;
|
||||||
@@ -54,6 +58,24 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
/// hat rein rechnerisch schon 100 %, das ist noch kein auffälliges Muster, nur eine zu kleine
|
/// hat rein rechnerisch schon 100 %, das ist noch kein auffälliges Muster, nur eine zu kleine
|
||||||
/// Stichprobe. Dieselbe Konstante wie GroupOverviewViewModel.AttendanceMinSampleSize.
|
/// Stichprobe. Dieselbe Konstante wie GroupOverviewViewModel.AttendanceMinSampleSize.
|
||||||
private const int AttendanceMinSampleSize = 8;
|
private const int AttendanceMinSampleSize = 8;
|
||||||
|
/// Nutzer-Entscheidung: ab 3 offenen/überfälligen Hausaufgaben im laufenden Schuljahr (alle
|
||||||
|
/// Gruppen) wird gewarnt. Keine Mindeststichprobe wie bei der Fehlzeitenquote nötig — das ist
|
||||||
|
/// hier ein absoluter Zähler, kein Anteil, der bei wenigen Terminen künstlich hoch ausfallen kann.
|
||||||
|
private const int MissingHomeworkWarningThreshold = 3;
|
||||||
|
/// Nutzer-Entscheidung: ab 8 Verspätungen (Late/SignificantlyLate) im laufenden Schuljahr
|
||||||
|
/// (alle Gruppen) wird gewarnt.
|
||||||
|
private const int LatenessWarningThreshold = 8;
|
||||||
|
/// Nutzer-Feedback: eine Warnung, zu der bereits ein offener Vorgang mit passendem Tag existiert
|
||||||
|
/// ODER die manuell zurückgestellt wurde, erscheint "entschärft" (grau, in der eingeklappten
|
||||||
|
/// "Zurückgestellt"-Gruppe, nicht mitgezählt) statt weiter rot hervorgehoben — aber nur befristet: bessert sich die zugrunde
|
||||||
|
/// liegende Zahl innerhalb dieser Frist nicht, soll die Warnung wieder auffallen, statt durch
|
||||||
|
/// einen dauerhaft offenen Vorgang für immer entschärft zu bleiben. Für den Vorgang-Fall zählt
|
||||||
|
/// dessen UpdatedAt (jede Interaktion setzt die Frist zurück); für "Zurückstellen" wählt die
|
||||||
|
/// Nutzerin die Frist selbst (siehe OnPickSnoozeDuration).
|
||||||
|
private const int VorgangDefusalGraceDays = 14;
|
||||||
|
private const string AbsentismusTag = "Absentismus";
|
||||||
|
private const string HausaufgabenTag = "Hausaufgaben";
|
||||||
|
private const string VerspaetungenTag = "Verspätungen";
|
||||||
/// Nutzer-Feedback: "ich vergesse es, und fasse die App auch außerhalb der Schule manchmal
|
/// Nutzer-Feedback: "ich vergesse es, und fasse die App auch außerhalb der Schule manchmal
|
||||||
/// nicht mehr an" — die Erinnerung an fehlende Unterrichtszeit-Erfassung schaut deshalb nicht
|
/// nicht mehr an" — die Erinnerung an fehlende Unterrichtszeit-Erfassung schaut deshalb nicht
|
||||||
/// nur auf heute zurück, sondern auf ein paar Tage, damit ein vergessener Tag nicht verloren
|
/// nur auf heute zurück, sondern auf ein paar Tage, damit ein vergessener Tag nicht verloren
|
||||||
@@ -107,6 +129,8 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
|
|
||||||
private readonly List<OpenExcuseItem> _excuses = [];
|
private readonly List<OpenExcuseItem> _excuses = [];
|
||||||
private readonly List<AttentionItem> _attendanceItems = [];
|
private readonly List<AttentionItem> _attendanceItems = [];
|
||||||
|
private readonly List<AttentionItem> _missingHomeworkItems = [];
|
||||||
|
private readonly List<AttentionItem> _latenessItems = [];
|
||||||
private readonly List<AttentionItem> _supportItems = [];
|
private readonly List<AttentionItem> _supportItems = [];
|
||||||
private readonly List<AttentionItem> _correctionItems = [];
|
private readonly List<AttentionItem> _correctionItems = [];
|
||||||
private readonly List<AttentionItem> _unplannedItems = [];
|
private readonly List<AttentionItem> _unplannedItems = [];
|
||||||
@@ -119,10 +143,13 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
private static readonly (AttentionKind Kind, string Header)[] AttentionGroupOrder =
|
private static readonly (AttentionKind Kind, string Header)[] AttentionGroupOrder =
|
||||||
[
|
[
|
||||||
(AttentionKind.MissingTeachingTime, "Unterrichtszeit nacherfassen"),
|
(AttentionKind.MissingTeachingTime, "Unterrichtszeit nacherfassen"),
|
||||||
// Die Fehlzeitenquote ist auch in fremden Klassen unmittelbar relevant, waehrend offene
|
// Die Fehlzeitenquote, Hausaufgaben- und Verspätungs-Warnungen sind auch in fremden Klassen
|
||||||
// Entschuldigungen nur fuer die eigene Klasse bearbeitet werden koennen. Deshalb steht sie
|
// unmittelbar relevant, waehrend offene Entschuldigungen nur fuer die eigene Klasse bearbeitet
|
||||||
// im Dashboard vor den Entschuldigungen statt weiter unten zwischen den sonstigen Hinweisen.
|
// werden koennen. Deshalb stehen alle drei im Dashboard vor den Entschuldigungen statt weiter
|
||||||
|
// unten zwischen den sonstigen Hinweisen.
|
||||||
(AttentionKind.Attendance, "Fehlzeiten-Warnung"),
|
(AttentionKind.Attendance, "Fehlzeiten-Warnung"),
|
||||||
|
(AttentionKind.Lateness, "Verspätungen-Warnung"),
|
||||||
|
(AttentionKind.MissingHomework, "Hausaufgaben-Warnung"),
|
||||||
(AttentionKind.Excuse, "Offene Entschuldigungen"),
|
(AttentionKind.Excuse, "Offene Entschuldigungen"),
|
||||||
(AttentionKind.Correction, "Offene Korrekturen"),
|
(AttentionKind.Correction, "Offene Korrekturen"),
|
||||||
(AttentionKind.Unplanned, "Ungeplante Stunden"),
|
(AttentionKind.Unplanned, "Ungeplante Stunden"),
|
||||||
@@ -133,6 +160,14 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
// Navigation-Callback – wird von App.axaml.cs verdrahtet
|
// Navigation-Callback – wird von App.axaml.cs verdrahtet
|
||||||
public Action<Guid>? OnNavigateToGroup { get; set; }
|
public Action<Guid>? OnNavigateToGroup { get; set; }
|
||||||
public Action<Guid>? OnNavigateToStudent { get; set; }
|
public Action<Guid>? OnNavigateToStudent { get; set; }
|
||||||
|
// Sprungziel für die drei klassenübergreifenden Warnungen (Fehlzeiten/Hausaufgaben/Verspätungen)
|
||||||
|
// direkt auf den "Vorgänge"-Tab des Schülerdetails (Guid Schüler, string vorgeschlagenes Tag,
|
||||||
|
// string vorgeschlagener Titel) — eigenes Delegate statt OnNavigateToStudent zu erweitern, damit
|
||||||
|
// dessen übrige Aufrufer (Förderplan, Auffälligkeiten, Termine) unverändert bleiben.
|
||||||
|
public Action<Guid, string, string>? OnNavigateToStudentCase { get; set; }
|
||||||
|
// Fragt beim Klick auf "Zurückstellen" die gewünschte Frist ab (Anzeigetext, z.B. "Fehlzeiten –
|
||||||
|
// Anna Beispiel") und liefert die Anzahl Tage zurück, oder null bei Abbruch.
|
||||||
|
public Func<string, Task<int?>>? OnPickSnoozeDuration { get; set; }
|
||||||
// Sprungziel eigens für eine Stunde in TodaysLessons (9.2) — bewusst getrennt von
|
// Sprungziel eigens für eine Stunde in TodaysLessons (9.2) — bewusst getrennt von
|
||||||
// OnNavigateToGroup (Lerngruppen-Kacheln, Tab "Übersicht"), da der Sprung von einer konkreten
|
// OnNavigateToGroup (Lerngruppen-Kacheln, Tab "Übersicht"), da der Sprung von einer konkreten
|
||||||
// Stunde aus sinnvollerweise direkt in die Mitarbeitserfassung führt.
|
// Stunde aus sinnvollerweise direkt in die Mitarbeitserfassung führt.
|
||||||
@@ -159,8 +194,16 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
public int TodayLessonCount => TodaysLessons.Count;
|
public int TodayLessonCount => TodaysLessons.Count;
|
||||||
public int OpenTaskCount => OpenTasks.Count;
|
public int OpenTaskCount => OpenTasks.Count;
|
||||||
public int UpcomingCount => UpcomingDates.Count;
|
public int UpcomingCount => UpcomingDates.Count;
|
||||||
public int AttentionCount => _excuses.Count + _attendanceItems.Count + _supportItems.Count
|
/// Zurückgestellte/entschärfte Warnungen zählen bewusst nicht mit (Nutzer-Feedback) — sie stehen
|
||||||
+ _correctionItems.Count + _unplannedItems.Count + _alertItems.Count + _missingTimeItems.Count;
|
/// eingeklappt in der eigenen "Zurückgestellt"-Gruppe, bis ihre Frist abläuft.
|
||||||
|
public int AttentionCount => _excuses.Count + _supportItems.Count
|
||||||
|
+ _correctionItems.Count + _unplannedItems.Count + _alertItems.Count + _missingTimeItems.Count
|
||||||
|
+ CrossClassWarnings.Count(i => !i.IsDefused);
|
||||||
|
/// Steuert den Hinweis "Keine offenen Punkte." — die eingeklappte "Zurückgestellt"-Gruppe allein
|
||||||
|
/// gilt nicht als offener Punkt.
|
||||||
|
public bool HasOpenAttention => Attention.Any(g => !g.IsDeferred);
|
||||||
|
private IEnumerable<AttentionItem> CrossClassWarnings =>
|
||||||
|
_attendanceItems.Concat(_latenessItems).Concat(_missingHomeworkItems);
|
||||||
public string TodayLessonSummary => TodayLessonCount == 1 ? "1 Stunde" : $"{TodayLessonCount} Stunden";
|
public string TodayLessonSummary => TodayLessonCount == 1 ? "1 Stunde" : $"{TodayLessonCount} Stunden";
|
||||||
public string OpenTaskSummary => OpenTaskCount == 1 ? "1 Aufgabe" : $"{OpenTaskCount} Aufgaben";
|
public string OpenTaskSummary => OpenTaskCount == 1 ? "1 Aufgabe" : $"{OpenTaskCount} Aufgaben";
|
||||||
public string AttentionSummary => AttentionCount == 1 ? "1 offener Punkt" : $"{AttentionCount} offene Punkte";
|
public string AttentionSummary => AttentionCount == 1 ? "1 offener Punkt" : $"{AttentionCount} offene Punkte";
|
||||||
@@ -175,7 +218,8 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
IReportGradeRepository reportGrades, IGroupMembershipRepository memberships,
|
IReportGradeRepository reportGrades, IGroupMembershipRepository memberships,
|
||||||
IWorkTaskRepository tasks, IParticipationSessionRepository participationSessions,
|
IWorkTaskRepository tasks, IParticipationSessionRepository participationSessions,
|
||||||
IParticipationRepository participationEntries, IStudentRepository students,
|
IParticipationRepository participationEntries, IStudentRepository students,
|
||||||
IDocumentationRepository documentation, ITimetableSlotRepository timetableSlots,
|
IDocumentationRepository documentation, IVorgangRepository vorgaenge,
|
||||||
|
IDashboardWarningSnoozeRepository warningSnoozes, ITimetableSlotRepository timetableSlots,
|
||||||
PeriodScheduleService periodSchedule, AttendanceBalanceService attendanceBalance, SchoolYearService sy,
|
PeriodScheduleService periodSchedule, AttendanceBalanceService attendanceBalance, SchoolYearService sy,
|
||||||
DashboardSettingsService dashboardSettings, ISchoolHolidayRepository schoolHolidays,
|
DashboardSettingsService dashboardSettings, ISchoolHolidayRepository schoolHolidays,
|
||||||
PublicHolidayService publicHolidays, SchoolCalendarSettingsService calendarSettings,
|
PublicHolidayService publicHolidays, SchoolCalendarSettingsService calendarSettings,
|
||||||
@@ -189,6 +233,7 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
_examResults = examResults; _grades = grades; _reportGrades = reportGrades; _memberships = memberships;
|
_examResults = examResults; _grades = grades; _reportGrades = reportGrades; _memberships = memberships;
|
||||||
_participationSessions = participationSessions; _participationEntries = participationEntries;
|
_participationSessions = participationSessions; _participationEntries = participationEntries;
|
||||||
_students = students; _documentation = documentation;
|
_students = students; _documentation = documentation;
|
||||||
|
_vorgaenge = vorgaenge; _warningSnoozes = warningSnoozes;
|
||||||
_timetableSlots = timetableSlots; _periodSchedule = periodSchedule;
|
_timetableSlots = timetableSlots; _periodSchedule = periodSchedule;
|
||||||
_attendanceBalance = attendanceBalance; _sy = sy; _dashboardSettings = dashboardSettings;
|
_attendanceBalance = attendanceBalance; _sy = sy; _dashboardSettings = dashboardSettings;
|
||||||
_schoolHolidays = schoolHolidays; _publicHolidays = publicHolidays; _calendarSettings = calendarSettings;
|
_schoolHolidays = schoolHolidays; _publicHolidays = publicHolidays; _calendarSettings = calendarSettings;
|
||||||
@@ -203,6 +248,11 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
// waeren Tests fuer "kurz vor/nach Ablauf einer Wartezeit" je nach Ausfuehrungsuhrzeit
|
// waeren Tests fuer "kurz vor/nach Ablauf einer Wartezeit" je nach Ausfuehrungsuhrzeit
|
||||||
// zufaellig rot oder gruen (siehe TODO.md, Abschnitt 9, Nachtrag Uhrzeit-Wraparound).
|
// zufaellig rot oder gruen (siehe TODO.md, Abschnitt 9, Nachtrag Uhrzeit-Wraparound).
|
||||||
_now = now ?? (() => DateTime.Now);
|
_now = now ?? (() => DateTime.Now);
|
||||||
|
// Bewusst hier aus den ohnehin injizierten Repositories gebaut statt als weiterer
|
||||||
|
// Konstruktor-Parameter — dieselben Datenquellen wie die Warnungen selbst, und die lange
|
||||||
|
// Parameterliste (inkl. aller Test-Aufrufer) bleibt unverändert.
|
||||||
|
_evidence = new StudentWarningEvidenceService(students, participationSessions, participationEntries,
|
||||||
|
groups, sy, attendanceBalance, _now);
|
||||||
if (annualPlanSync is not null)
|
if (annualPlanSync is not null)
|
||||||
{
|
{
|
||||||
annualPlanSync.DataChanged += () => Avalonia.Threading.Dispatcher.UIThread.Post(LoadCalendar);
|
annualPlanSync.DataChanged += () => Avalonia.Threading.Dispatcher.UIThread.Post(LoadCalendar);
|
||||||
@@ -286,6 +336,8 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
LoadCalendar();
|
LoadCalendar();
|
||||||
LoadOpenExcuses(groups.Values.ToList(), today);
|
LoadOpenExcuses(groups.Values.ToList(), today);
|
||||||
LoadAttendanceWarnings(today);
|
LoadAttendanceWarnings(today);
|
||||||
|
LoadMissingHomeworkWarnings(today);
|
||||||
|
LoadLatenessWarnings(today);
|
||||||
LoadExamWeekLoads(groups, today);
|
LoadExamWeekLoads(groups, today);
|
||||||
LoadMissingTeachingTime(today);
|
LoadMissingTeachingTime(today);
|
||||||
LoadSupportPlanReviews(today);
|
LoadSupportPlanReviews(today);
|
||||||
@@ -305,7 +357,9 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
UpcomingCard.IsEmpty = UpcomingDates.Count == 0;
|
UpcomingCard.IsEmpty = UpcomingDates.Count == 0;
|
||||||
ExamLoadCard.IsEmpty = ExamWeekLoads.Count == 0;
|
ExamLoadCard.IsEmpty = ExamWeekLoads.Count == 0;
|
||||||
GroupsCard.IsEmpty = CurrentGroups.Count == 0;
|
GroupsCard.IsEmpty = CurrentGroups.Count == 0;
|
||||||
AttentionCard.IsEmpty = AttentionCount == 0;
|
// Nicht über AttentionCount: die Kachel muss auch dann stehen bleiben, wenn nur noch
|
||||||
|
// zurückgestellte Warnungen übrig sind, sonst wären diese bis zum Fristablauf unerreichbar.
|
||||||
|
AttentionCard.IsEmpty = AttentionCount == 0 && !CrossClassWarnings.Any();
|
||||||
|
|
||||||
// Erst nachdem alle IsEmpty-Werte stehen: welche Kachel tatsaechlich gerendert wird, haengt
|
// Erst nachdem alle IsEmpty-Werte stehen: welche Kachel tatsaechlich gerendert wird, haengt
|
||||||
// ueber EffectiveIsVisible daran, und davon wiederum die Zeilen-/Spaltenzuordnung.
|
// ueber EffectiveIsVisible daran, und davon wiederum die Zeilen-/Spaltenzuordnung.
|
||||||
@@ -374,16 +428,95 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
|
|
||||||
// ── Fehlzeiten-Warnung (5.2.3) ────────────────────────────────────────────
|
// ── Fehlzeiten-Warnung (5.2.3) ────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Ein Bulk-Laden aller Sitzungen vermeidet, für jeden Mitarbeits-Eintrag jedes Schülers einzeln
|
||||||
|
/// GetById aufzurufen (N+1 bei vielen Schülern/Einträgen) — von allen drei klassenübergreifenden
|
||||||
|
/// Warnungen (Fehlzeiten/Hausaufgaben/Verspätungen) genutzt.
|
||||||
|
private Dictionary<Guid, DateOnly> BuildSessionDateLookup() =>
|
||||||
|
_participationSessions.GetAll().ToDictionary(s => s.Id, s => s.Date);
|
||||||
|
|
||||||
|
// ── Entschärfen (Nutzer-Feedback) ─────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// Eine der drei klassenübergreifenden Warnungen gilt als "entschärft" (grau, in der
|
||||||
|
// eingeklappten "Zurückgestellt"-Gruppe, siehe RebuildAttention), solange entweder ein offener Vorgang mit passendem Tag kürzlich bearbeitet
|
||||||
|
// wurde, oder eine manuelle Rückstellung noch läuft — beides zeitlich befristet (siehe
|
||||||
|
// VorgangDefusalGraceDays-Kommentar), damit ausbleibende Besserung nach Fristablauf wieder
|
||||||
|
// auffällt statt dauerhaft entschärft zu bleiben. Beide Nachschlage-Mengen bulk-geladen wie
|
||||||
|
// BuildSessionDateLookup, um kein N+1 über alle Schüler/Vorgänge zu erzeugen.
|
||||||
|
|
||||||
|
private HashSet<(Guid StudentId, string Tag)> BuildRecentVorgangTagSet()
|
||||||
|
{
|
||||||
|
var cutoffUtc = DateTime.UtcNow.AddDays(-VorgangDefusalGraceDays);
|
||||||
|
var set = new HashSet<(Guid, string)>();
|
||||||
|
foreach (var v in _vorgaenge.GetAll())
|
||||||
|
{
|
||||||
|
if (v.Status != VorgangStatus.Open) continue;
|
||||||
|
// Siehe CLAUDE.md (LiteDB-Details): DateTime-Vergleiche nach dem Utc→Local-Roundtrip
|
||||||
|
// sind nur nach beidseitigem ToUniversalTime() sicher.
|
||||||
|
if (v.UpdatedAt.ToUniversalTime() < cutoffUtc) continue;
|
||||||
|
foreach (var studentId in v.StudentIds)
|
||||||
|
foreach (var tag in v.Tags)
|
||||||
|
set.Add((studentId, tag.ToLowerInvariant()));
|
||||||
|
}
|
||||||
|
return set;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bei doppelten Einträgen für dasselbe Paar (z.B. Altbestand vor der abgeleiteten Id) zählt die
|
||||||
|
// längste noch laufende Frist.
|
||||||
|
private Dictionary<(Guid StudentId, string Tag), DateOnly> BuildActiveSnoozeSet(DateOnly today) =>
|
||||||
|
_warningSnoozes.GetAll().Where(s => s.SnoozedUntil >= today)
|
||||||
|
.GroupBy(s => (s.StudentId, s.WarningTag.ToLowerInvariant()))
|
||||||
|
.ToDictionary(g => g.Key, g => g.Max(s => s.SnoozedUntil));
|
||||||
|
|
||||||
|
/// Grund, warum eine Warnung entschärft ist, als Untertitel für die "Zurückgestellt"-Gruppe
|
||||||
|
/// (dort stehen alle drei Warnarten gemischt, deshalb mit Art-Präfix) — null, wenn sie scharf ist.
|
||||||
|
/// Eine manuelle Rückstellung hat Vorrang, weil sie ein konkretes Ablaufdatum nennen kann.
|
||||||
|
private static string? DefusalReason(Guid studentId, string tag, string kindLabel,
|
||||||
|
HashSet<(Guid StudentId, string Tag)> recentVorgaenge,
|
||||||
|
Dictionary<(Guid StudentId, string Tag), DateOnly> activeSnoozes)
|
||||||
|
{
|
||||||
|
var key = (studentId, tag.ToLowerInvariant());
|
||||||
|
if (activeSnoozes.TryGetValue(key, out var until))
|
||||||
|
return $"{kindLabel} · zurückgestellt bis {until:dd.MM.}";
|
||||||
|
return recentVorgaenge.Contains(key) ? $"{kindLabel} · Vorgang in Bearbeitung" : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Von der "Zurückstellen"-Aktion einer Warnung aufgerufen (siehe ToAttentionItem-Überladungen
|
||||||
|
/// unten) — fragt über OnPickSnoozeDuration die Frist ab und speichert sie, sofern nicht
|
||||||
|
/// abgebrochen. Aktualisiert danach nur die drei klassenübergreifenden Warnungen neu, kein
|
||||||
|
/// voller Dashboard-Reload nötig (gleiches Muster wie ResolveExcuse/AddMissingTeachingTime).
|
||||||
|
private async Task SnoozeWarningAsync(Guid studentId, string tag, string label)
|
||||||
|
{
|
||||||
|
if (OnPickSnoozeDuration is null) return;
|
||||||
|
var days = await OnPickSnoozeDuration(label);
|
||||||
|
if (days is null) return;
|
||||||
|
|
||||||
|
var snooze = _warningSnoozes.Get(studentId, tag) ?? new DashboardWarningSnooze
|
||||||
|
{ StudentId = studentId, WarningTag = tag };
|
||||||
|
snooze.SnoozedUntil = DateOnly.FromDateTime(_now()).AddDays(days.Value);
|
||||||
|
_warningSnoozes.Save(snooze);
|
||||||
|
|
||||||
|
var today = DateOnly.FromDateTime(_now());
|
||||||
|
LoadAttendanceWarnings(today);
|
||||||
|
LoadMissingHomeworkWarnings(today);
|
||||||
|
LoadLatenessWarnings(today);
|
||||||
|
RebuildAttention();
|
||||||
|
UpdateDashboardSummary();
|
||||||
|
}
|
||||||
|
|
||||||
|
private AttentionAction SnoozeAction(Guid studentId, string tag, string label) => new("Zurückstellen",
|
||||||
|
new AsyncRelayCommand(() => SnoozeWarningAsync(studentId, tag, label)));
|
||||||
|
|
||||||
|
// ── Fehlzeiten-Warnung (5.2.3) ────────────────────────────────────────────
|
||||||
|
|
||||||
private void LoadAttendanceWarnings(DateOnly today)
|
private void LoadAttendanceWarnings(DateOnly today)
|
||||||
{
|
{
|
||||||
_attendanceItems.Clear();
|
_attendanceItems.Clear();
|
||||||
var schoolYear = _sy.CurrentSchoolYear();
|
var schoolYear = _sy.CurrentSchoolYear();
|
||||||
var from = _sy.SchoolYearStart(schoolYear);
|
var from = _sy.SchoolYearStart(schoolYear);
|
||||||
var to = _sy.SchoolYearEnd(schoolYear);
|
var to = _sy.SchoolYearEnd(schoolYear);
|
||||||
|
var sessionDates = BuildSessionDateLookup();
|
||||||
// Ein Bulk-Laden aller Sitzungen vermeidet, für jeden Mitarbeits-Eintrag jedes Schülers
|
var recentVorgaenge = BuildRecentVorgangTagSet();
|
||||||
// einzeln GetById aufzurufen (N+1 bei vielen Schülern/Einträgen).
|
var activeSnoozes = BuildActiveSnoozeSet(today);
|
||||||
var sessionDates = _participationSessions.GetAll().ToDictionary(s => s.Id, s => s.Date);
|
|
||||||
|
|
||||||
var items = new List<AttendanceWarningItem>();
|
var items = new List<AttendanceWarningItem>();
|
||||||
foreach (var student in _students.GetAll())
|
foreach (var student in _students.GetAll())
|
||||||
@@ -398,13 +531,93 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
if (balance.TotalChecked >= AttendanceMinSampleSize && balance.ExceedsThreshold)
|
if (balance.TotalChecked >= AttendanceMinSampleSize && balance.ExceedsThreshold)
|
||||||
items.Add(new AttendanceWarningItem(student.Id, student.FullName, balance.AbsenceRatePercent));
|
items.Add(new AttendanceWarningItem(student.Id, student.FullName, balance.AbsenceRatePercent));
|
||||||
}
|
}
|
||||||
foreach (var item in items.OrderByDescending(i => i.AbsenceRatePercent))
|
var ordered = items
|
||||||
_attendanceItems.Add(ToAttentionItem(item));
|
.Select(i => (Item: i, Defused: DefusalReason(i.StudentId, AbsentismusTag, "Fehlzeiten", recentVorgaenge, activeSnoozes)))
|
||||||
|
.OrderByDescending(x => x.Item.AbsenceRatePercent);
|
||||||
|
foreach (var (item, defused) in ordered)
|
||||||
|
_attendanceItems.Add(ToAttentionItem(item, defused));
|
||||||
}
|
}
|
||||||
|
|
||||||
private AttentionItem ToAttentionItem(AttendanceWarningItem w) => new(
|
private AttentionItem ToAttentionItem(AttendanceWarningItem w, string? defusedReason) => new(
|
||||||
AttentionKind.Attendance, w.StudentName, trailingText: $"{w.AbsenceRatePercent:0.#} %",
|
AttentionKind.Attendance, w.StudentName, trailingText: $"{w.AbsenceRatePercent:0.#} %",
|
||||||
isWarningTrailing: true, navigate: () => OnNavigateToStudent?.Invoke(w.StudentId));
|
subtitle: defusedReason ?? "", isWarningTrailing: true, isDefused: defusedReason is not null,
|
||||||
|
actions: [SnoozeAction(w.StudentId, AbsentismusTag, $"Fehlzeiten – {w.StudentName}")],
|
||||||
|
navigate: () => OnNavigateToStudentCase?.Invoke(w.StudentId, AbsentismusTag, "Fehlzeiten"),
|
||||||
|
detailFactory: () => new StudentWarningDetailViewModel(AttentionKind.Attendance, _evidence.Build(w.StudentId)));
|
||||||
|
|
||||||
|
// ── Hausaufgaben-Warnung (Nutzer-Feedback: analog zur Fehlzeiten-Warnung, klassenübergreifend) ──
|
||||||
|
|
||||||
|
private void LoadMissingHomeworkWarnings(DateOnly today)
|
||||||
|
{
|
||||||
|
_missingHomeworkItems.Clear();
|
||||||
|
var schoolYear = _sy.CurrentSchoolYear();
|
||||||
|
var from = _sy.SchoolYearStart(schoolYear);
|
||||||
|
var to = _sy.SchoolYearEnd(schoolYear);
|
||||||
|
var sessionDates = BuildSessionDateLookup();
|
||||||
|
var recentVorgaenge = BuildRecentVorgangTagSet();
|
||||||
|
var activeSnoozes = BuildActiveSnoozeSet(today);
|
||||||
|
|
||||||
|
var items = new List<MissingHomeworkWarningItem>();
|
||||||
|
foreach (var student in _students.GetAll())
|
||||||
|
{
|
||||||
|
var count = _participationEntries.GetByStudent(student.Id)
|
||||||
|
.Count(e => sessionDates.TryGetValue(e.SessionId, out var date) && date >= from && date <= to
|
||||||
|
&& HomeworkDisplay.CountsAsMissing(HomeworkDisplay.Effective(e)));
|
||||||
|
if (count >= MissingHomeworkWarningThreshold)
|
||||||
|
items.Add(new MissingHomeworkWarningItem(student.Id, student.FullName, count));
|
||||||
|
}
|
||||||
|
var ordered = items
|
||||||
|
.Select(i => (Item: i, Defused: DefusalReason(i.StudentId, HausaufgabenTag, "Hausaufgaben", recentVorgaenge, activeSnoozes)))
|
||||||
|
.OrderByDescending(x => x.Item.MissingCount);
|
||||||
|
foreach (var (item, defused) in ordered)
|
||||||
|
_missingHomeworkItems.Add(ToAttentionItem(item, defused));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AttentionItem ToAttentionItem(MissingHomeworkWarningItem w, string? defusedReason) => new(
|
||||||
|
AttentionKind.MissingHomework, w.StudentName, trailingText: $"{w.MissingCount} offen",
|
||||||
|
subtitle: defusedReason ?? "", isWarningTrailing: true, isDefused: defusedReason is not null,
|
||||||
|
actions: [SnoozeAction(w.StudentId, HausaufgabenTag, $"Hausaufgaben – {w.StudentName}")],
|
||||||
|
navigate: () => OnNavigateToStudentCase?.Invoke(w.StudentId, HausaufgabenTag, "Hausaufgaben"),
|
||||||
|
detailFactory: () => new StudentWarningDetailViewModel(AttentionKind.MissingHomework, _evidence.Build(w.StudentId)));
|
||||||
|
|
||||||
|
// ── Verspätungs-Warnung (Nutzer-Feedback: analog zur Fehlzeiten-Warnung, klassenübergreifend) ──
|
||||||
|
//
|
||||||
|
// Late/SignificantlyLate zählen bewusst NICHT in AttendanceBalanceService.Calculate hinein (dort
|
||||||
|
// gelten sie als Present für die Fehlzeitenquote, siehe Klassenkommentar dort) — diese Zählung
|
||||||
|
// läuft deshalb unabhängig davon direkt über die rohen ParticipationEntry-Einträge.
|
||||||
|
|
||||||
|
private void LoadLatenessWarnings(DateOnly today)
|
||||||
|
{
|
||||||
|
_latenessItems.Clear();
|
||||||
|
var schoolYear = _sy.CurrentSchoolYear();
|
||||||
|
var from = _sy.SchoolYearStart(schoolYear);
|
||||||
|
var to = _sy.SchoolYearEnd(schoolYear);
|
||||||
|
var sessionDates = BuildSessionDateLookup();
|
||||||
|
var recentVorgaenge = BuildRecentVorgangTagSet();
|
||||||
|
var activeSnoozes = BuildActiveSnoozeSet(today);
|
||||||
|
|
||||||
|
var items = new List<LatenessWarningItem>();
|
||||||
|
foreach (var student in _students.GetAll())
|
||||||
|
{
|
||||||
|
var count = _participationEntries.GetByStudent(student.Id)
|
||||||
|
.Count(e => sessionDates.TryGetValue(e.SessionId, out var date) && date >= from && date <= to
|
||||||
|
&& e.Attendance is AttendanceStatus.Late or AttendanceStatus.SignificantlyLate);
|
||||||
|
if (count >= LatenessWarningThreshold)
|
||||||
|
items.Add(new LatenessWarningItem(student.Id, student.FullName, count));
|
||||||
|
}
|
||||||
|
var ordered = items
|
||||||
|
.Select(i => (Item: i, Defused: DefusalReason(i.StudentId, VerspaetungenTag, "Verspätungen", recentVorgaenge, activeSnoozes)))
|
||||||
|
.OrderByDescending(x => x.Item.LateCount);
|
||||||
|
foreach (var (item, defused) in ordered)
|
||||||
|
_latenessItems.Add(ToAttentionItem(item, defused));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AttentionItem ToAttentionItem(LatenessWarningItem w, string? defusedReason) => new(
|
||||||
|
AttentionKind.Lateness, w.StudentName, trailingText: $"{w.LateCount}× verspätet",
|
||||||
|
subtitle: defusedReason ?? "", isWarningTrailing: true, isDefused: defusedReason is not null,
|
||||||
|
actions: [SnoozeAction(w.StudentId, VerspaetungenTag, $"Verspätungen – {w.StudentName}")],
|
||||||
|
navigate: () => OnNavigateToStudentCase?.Invoke(w.StudentId, VerspaetungenTag, "Verspätungen"),
|
||||||
|
detailFactory: () => new StudentWarningDetailViewModel(AttentionKind.Lateness, _evidence.Build(w.StudentId)));
|
||||||
|
|
||||||
// ── Klausurwochen (Nutzer-Feedback) ───────────────────────────────────────
|
// ── Klausurwochen (Nutzer-Feedback) ───────────────────────────────────────
|
||||||
//
|
//
|
||||||
@@ -757,19 +970,33 @@ public partial class DashboardViewModel : ObservableObject
|
|||||||
[AttentionKind.Unplanned] = _unplannedItems,
|
[AttentionKind.Unplanned] = _unplannedItems,
|
||||||
[AttentionKind.Alert] = _alertItems,
|
[AttentionKind.Alert] = _alertItems,
|
||||||
[AttentionKind.Attendance] = _attendanceItems,
|
[AttentionKind.Attendance] = _attendanceItems,
|
||||||
|
[AttentionKind.MissingHomework] = _missingHomeworkItems,
|
||||||
|
[AttentionKind.Lateness] = _latenessItems,
|
||||||
[AttentionKind.SupportPlan] = _supportItems,
|
[AttentionKind.SupportPlan] = _supportItems,
|
||||||
};
|
};
|
||||||
|
|
||||||
Attention.Clear();
|
Attention.Clear();
|
||||||
|
var deferred = new List<AttentionItem>();
|
||||||
foreach (var (kind, header) in AttentionGroupOrder)
|
foreach (var (kind, header) in AttentionGroupOrder)
|
||||||
{
|
{
|
||||||
if (!IsAttentionFilterActive(kind)) continue;
|
if (!IsAttentionFilterActive(kind)) continue;
|
||||||
var items = byKind[kind];
|
var items = byKind[kind].Where(i => !i.IsDefused).ToList();
|
||||||
|
deferred.AddRange(byKind[kind].Where(i => i.IsDefused));
|
||||||
if (items.Count == 0) continue;
|
if (items.Count == 0) continue;
|
||||||
Attention.Add(new AttentionGroup(kind, header, items));
|
Attention.Add(new AttentionGroup(kind, header, items));
|
||||||
}
|
}
|
||||||
|
// Entschärfte Warnungen aller drei klassenübergreifenden Arten gesammelt ganz unten und
|
||||||
|
// eingeklappt (Nutzer-Feedback), statt grau in ihrer jeweiligen Gruppe mitzulaufen. Der
|
||||||
|
// Aufklapp-Zustand überlebt das Neuaufbauen der Gruppen (z.B. nach einem Zurückstellen).
|
||||||
|
if (deferred.Count > 0)
|
||||||
|
Attention.Add(new AttentionGroup(null, "Zurückgestellt", deferred,
|
||||||
|
isDeferred: true, isExpanded: _deferredGroupExpanded,
|
||||||
|
onExpandedChanged: expanded => _deferredGroupExpanded = expanded));
|
||||||
|
OnPropertyChanged(nameof(HasOpenAttention));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bool _deferredGroupExpanded;
|
||||||
|
|
||||||
private static AttentionItem ToAttentionItem(OpenExcuseItem e) => new(
|
private static AttentionItem ToAttentionItem(OpenExcuseItem e) => new(
|
||||||
AttentionKind.Excuse, e.StudentName, subtitle: $"{e.GroupName} · {e.DateDisplay}",
|
AttentionKind.Excuse, e.StudentName, subtitle: $"{e.GroupName} · {e.DateDisplay}",
|
||||||
actions: [new AttentionAction("Entschuldigt", e.MarkExcusedCommand),
|
actions: [new AttentionAction("Entschuldigt", e.MarkExcusedCommand),
|
||||||
@@ -1200,6 +1427,20 @@ public class AttendanceWarningItem(Guid studentId, string studentName, double ab
|
|||||||
public double AbsenceRatePercent { get; } = absenceRatePercent;
|
public double AbsenceRatePercent { get; } = absenceRatePercent;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class MissingHomeworkWarningItem(Guid studentId, string studentName, int missingCount)
|
||||||
|
{
|
||||||
|
public Guid StudentId { get; } = studentId;
|
||||||
|
public string StudentName { get; } = studentName;
|
||||||
|
public int MissingCount { get; } = missingCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class LatenessWarningItem(Guid studentId, string studentName, int lateCount)
|
||||||
|
{
|
||||||
|
public Guid StudentId { get; } = studentId;
|
||||||
|
public string StudentName { get; } = studentName;
|
||||||
|
public int LateCount { get; } = lateCount;
|
||||||
|
}
|
||||||
|
|
||||||
public class ExamWeekLoadItem(int isoWeek, DateOnly weekStart, DateOnly weekEnd, int examCount)
|
public class ExamWeekLoadItem(int isoWeek, DateOnly weekStart, DateOnly weekEnd, int examCount)
|
||||||
{
|
{
|
||||||
public int ExamCount { get; } = examCount;
|
public int ExamCount { get; } = examCount;
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ public partial class ExamsOverviewViewModel : ObservableObject
|
|||||||
|
|
||||||
public Func<Exam, Task>? OnGradeExam { get; set; }
|
public Func<Exam, Task>? OnGradeExam { get; set; }
|
||||||
public Func<Exam, Task>? OnEvaluateExam { get; set; }
|
public Func<Exam, Task>? OnEvaluateExam { get; set; }
|
||||||
|
public Func<Exam, Task>? OnRevealExam { get; set; }
|
||||||
|
public Func<Exam, Task>? OnCoverSheets { get; set; }
|
||||||
public Action<Guid>? OnNavigateToGroup { get; set; }
|
public Action<Guid>? OnNavigateToGroup { get; set; }
|
||||||
public Action? OnNavigateToGroups { get; set; }
|
public Action? OnNavigateToGroups { get; set; }
|
||||||
public bool HasNoExams => Rows.Count == 0;
|
public bool HasNoExams => Rows.Count == 0;
|
||||||
@@ -169,6 +171,20 @@ public partial class ExamsOverviewViewModel : ObservableObject
|
|||||||
Load();
|
Load();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private async Task RevealSelected()
|
||||||
|
{
|
||||||
|
if (SelectedRow is null || OnRevealExam is null) return;
|
||||||
|
await OnRevealExam(SelectedRow.Exam);
|
||||||
|
}
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private async Task CoverSheetsSelected()
|
||||||
|
{
|
||||||
|
if (SelectedRow is null || OnCoverSheets is null) return;
|
||||||
|
await OnCoverSheets(SelectedRow.Exam);
|
||||||
|
}
|
||||||
|
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
private void GoToGroup()
|
private void GoToGroup()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,181 @@
|
|||||||
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
/// <summary>Erzeugt zu einer Klausur einen Satz individueller Deckblätter als ein Sammel-PDF.
|
||||||
|
/// Zur Auswahl stehen nur Vorlagen mit <c>report-type=exam-cover</c>, egal in welcher der beiden
|
||||||
|
/// Vorlagenbibliotheken sie importiert wurden. Mit <see cref="FillResults"/> trägt dieselbe
|
||||||
|
/// Vorlage Punkte und Note ein oder bleibt als Blanko-Deckblatt zum Ausfüllen von Hand.</summary>
|
||||||
|
public partial class ExamCoverSheetDialogViewModel : ObservableObject
|
||||||
|
{
|
||||||
|
private readonly Exam _exam;
|
||||||
|
private readonly LearningGroup _group;
|
||||||
|
private readonly string _subjectName;
|
||||||
|
private readonly GradingService _grading;
|
||||||
|
private readonly TemplateStore _loader;
|
||||||
|
private readonly ITemplateBatchRenderer _renderer;
|
||||||
|
private readonly Exam? _original;
|
||||||
|
private readonly Dictionary<Guid, ExamResult> _originalResults;
|
||||||
|
[ObservableProperty] private ReportInterimRunChoice? _selectedInterimRun;
|
||||||
|
[ObservableProperty] private bool _usesInterimGrades;
|
||||||
|
public ObservableCollection<ReportInterimRunChoice> InterimRuns { get; } = [];
|
||||||
|
|
||||||
|
partial void OnSelectedTemplateChanged(LetterTemplateChoice? value)
|
||||||
|
{
|
||||||
|
UsesInterimGrades = value is not null &&
|
||||||
|
DrawingBoxLocator.Find(_loader.Load(value.Model), ReportTextDrawing.InterimGrades) is not null;
|
||||||
|
}
|
||||||
|
|
||||||
|
[ObservableProperty] private LetterTemplateChoice? _selectedTemplate;
|
||||||
|
[ObservableProperty] private bool _fillResults;
|
||||||
|
[ObservableProperty] private string _statusMessage = "";
|
||||||
|
/// <summary>Vorbelegt aus den Einstellungen, hier nur für diesen Druck änderbar (z. B. zwei
|
||||||
|
/// Kürzel bei einem gemeinsam unterrichteten Kurs) — die Einstellung bleibt unberührt.</summary>
|
||||||
|
[ObservableProperty] private string _teacherAbbreviation;
|
||||||
|
/// <summary>Vorbelegt mit dem internen Klausurtitel, hier nur für diesen Druck änderbar — der
|
||||||
|
/// Titel der Klausur bleibt unberührt. Leer gelassen gilt wieder der interne Titel.</summary>
|
||||||
|
[ObservableProperty] private string _coverTitle;
|
||||||
|
[ObservableProperty, NotifyPropertyChangedFor(nameof(CanGenerate))] private bool _isGenerating;
|
||||||
|
[ObservableProperty] private int _progressValue;
|
||||||
|
[ObservableProperty] private int _progressMaximum = 1;
|
||||||
|
/// <summary>Alle Deckblätter sind gesetzt, das Sammel-PDF entsteht — dieser Schritt meldet
|
||||||
|
/// keinen Zwischenstand, der Balken läuft deshalb unbestimmt.</summary>
|
||||||
|
[ObservableProperty] private bool _isMerging;
|
||||||
|
[ObservableProperty] private string _progressText = "";
|
||||||
|
|
||||||
|
public string ExamTitle => _exam.Title;
|
||||||
|
public string ExamLabel => $"{_exam.Title} · {_group.Name} · {_exam.Date:dd.MM.yyyy}";
|
||||||
|
public ObservableCollection<LetterTemplateChoice> Templates { get; } = [];
|
||||||
|
public ObservableCollection<ExamCoverStudentChoice> Students { get; } = [];
|
||||||
|
public bool HasNoTemplates => Templates.Count == 0;
|
||||||
|
public bool CanGenerate => !HasNoTemplates && !IsGenerating;
|
||||||
|
public string SuggestedFileName => SanitizeFileName($"Deckblätter_{_group.Name}_{_exam.Title}.pdf");
|
||||||
|
|
||||||
|
public ExamCoverSheetDialogViewModel(Exam exam, LearningGroup group, string subjectName,
|
||||||
|
IStudentRepository students, IGroupMembershipRepository memberships, IExamResultRepository results,
|
||||||
|
GradingService grading, IReadOnlyList<TemplateStore> templateStores, ITemplateBatchRenderer renderer,
|
||||||
|
string teacherAbbreviation = "", IExamRepository? exams = null, IInterimGradeRepository? interims = null)
|
||||||
|
{
|
||||||
|
_teacherAbbreviation = teacherAbbreviation;
|
||||||
|
_coverTitle = exam.Title;
|
||||||
|
_exam = exam; _group = group; _subjectName = subjectName; _grading = grading; _renderer = renderer;
|
||||||
|
_loader = templateStores[0];
|
||||||
|
_original = exam.RepeatOfExamId is { } originalId ? exams?.GetById(originalId) : null;
|
||||||
|
_originalResults = exam.RepeatOfExamId is { } firstId
|
||||||
|
? results.GetByExam(firstId).ToDictionary(r => r.StudentId) : [];
|
||||||
|
foreach (var run in (interims?.GetByGroup(group.Id) ?? [])
|
||||||
|
.GroupBy(g => (g.Date, g.Occasion)).OrderByDescending(g => g.Key.Date).ThenBy(g => g.Key.Occasion))
|
||||||
|
InterimRuns.Add(new(run.Key.Date, run.Key.Occasion, run.ToList()));
|
||||||
|
// Bewusste Auswahl statt stillschweigend den neuesten Zwischenstand zu drucken.
|
||||||
|
foreach (var template in templateStores.SelectMany(x => x.GetTemplates()).Where(x => x.IsExamCover)
|
||||||
|
.DistinctBy(x => x.Id).OrderBy(x => x.Name, StringComparer.CurrentCultureIgnoreCase))
|
||||||
|
Templates.Add(new(template));
|
||||||
|
SelectedTemplate = Templates.FirstOrDefault();
|
||||||
|
|
||||||
|
var membershipList = memberships.GetByGroup(group.Id);
|
||||||
|
var existing = results.GetByExam(exam.Id).ToDictionary(r => r.StudentId);
|
||||||
|
var wroteOriginal = ExamParticipantService.WroteOriginal(exam, results.GetByExam);
|
||||||
|
foreach (var student in students.GetByGroup(group.Id).OrderBy(s => s.LastName).ThenBy(s => s.FirstName))
|
||||||
|
{
|
||||||
|
var membership = membershipList.FirstOrDefault(m => m.StudentId == student.Id);
|
||||||
|
existing.TryGetValue(student.Id, out var result);
|
||||||
|
if (!ExamParticipantService.Includes(exam, membership, result is not null, wroteOriginal.Contains(student.Id)))
|
||||||
|
continue;
|
||||||
|
Students.Add(new(student, result, membership?.Niveau));
|
||||||
|
}
|
||||||
|
// Vor der Korrektur ist das Blanko-Deckblatt der Normalfall, danach das ausgefüllte.
|
||||||
|
FillResults = Students.Any(s => s.IsCorrected);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Schreibt das Sammel-PDF und meldet den Erfolg. Gesetzt wird im Hintergrund, damit
|
||||||
|
/// der Dialog bei einem Klassensatz bedienbar bleibt und den Fortschritt zeigen kann.</summary>
|
||||||
|
public async Task<bool> GenerateAsync(string outputPath)
|
||||||
|
{
|
||||||
|
StatusMessage = "";
|
||||||
|
if (SelectedTemplate is null || IsGenerating) return false;
|
||||||
|
var included = Students.Where(s => s.IsIncluded).ToList();
|
||||||
|
if (included.Count == 0) { StatusMessage = "Kein Schüler ausgewählt."; return false; }
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var loaded = _loader.Load(SelectedTemplate.Model);
|
||||||
|
if (UsesInterimGrades && SelectedInterimRun is null)
|
||||||
|
{ StatusMessage = "Bitte einen gespeicherten Notenzwischenstand auswählen."; return false; }
|
||||||
|
if (UsesInterimGrades)
|
||||||
|
{
|
||||||
|
var missing = included.Where(s => !SelectedInterimRun!.Grades.Any(g => g.StudentId == s.Model.Id)).ToList();
|
||||||
|
if (missing.Count > 0)
|
||||||
|
{ StatusMessage = "Im gewählten Zwischenstand fehlen: " + string.Join(", ", missing.Select(s => s.FullName)) + ". Bitte Schüler abwählen oder einen anderen Durchgang wählen."; return false; }
|
||||||
|
}
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Now);
|
||||||
|
var data = included.Select(s => (ITemplateDataProvider)new LetterDataProvider(
|
||||||
|
ExamCoverPlaceholderBuilder.Build(_exam, _group, _subjectName, s.Model, s.Result, FillResults,
|
||||||
|
_grading, loaded, today, s.Niveau, TeacherAbbreviation, CoverTitle,
|
||||||
|
_original, _originalResults.GetValueOrDefault(s.Model.Id),
|
||||||
|
UsesInterimGrades ? SelectedInterimRun!.Grades.Single(g => g.StudentId == s.Model.Id) : null))).ToList();
|
||||||
|
ReportProgress(0, included.Count);
|
||||||
|
IsGenerating = true;
|
||||||
|
var progress = new Progress<int>(done => ReportProgress(done, included.Count));
|
||||||
|
var result = await Task.Run(() =>
|
||||||
|
{
|
||||||
|
var rendered = _renderer.RenderBatchToPdf(loaded, data, progress);
|
||||||
|
File.WriteAllBytes(outputPath, rendered.Pdf);
|
||||||
|
return rendered;
|
||||||
|
});
|
||||||
|
|
||||||
|
var message = $"{included.Count} Deckblätter erzeugt.";
|
||||||
|
var blank = FillResults ? included.Count(s => !s.IsCorrected) : 0;
|
||||||
|
if (blank > 0) message += $" {blank} davon ohne Punkte und Note (noch nicht korrigiert).";
|
||||||
|
var overflowing = result.PageCounts.Count(pages => pages > 1);
|
||||||
|
if (overflowing > 0)
|
||||||
|
message += $" Achtung: {overflowing} Deckblätter passen nicht auf eine Seite — die Punktetabelle braucht mehr Platz, als die Vorlage lässt.";
|
||||||
|
StatusMessage = message;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException or TemplateValidationException or QuestPDF.Drawing.Exceptions.DocumentLayoutException)
|
||||||
|
{ StatusMessage = $"Deckblätter konnten nicht erzeugt werden: {ex.Message}"; return false; }
|
||||||
|
finally { IsGenerating = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReportProgress(int done, int total)
|
||||||
|
{
|
||||||
|
ProgressMaximum = total;
|
||||||
|
ProgressValue = done;
|
||||||
|
IsMerging = done >= total && total > 1;
|
||||||
|
ProgressText = IsMerging
|
||||||
|
? "Sammel-PDF wird zusammengefügt …"
|
||||||
|
: $"{done} von {total} Deckblättern gesetzt …";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string SanitizeFileName(string value)
|
||||||
|
{ foreach (var character in Path.GetInvalidFileNameChars()) value = value.Replace(character, '_'); return value; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class ExamCoverStudentChoice : ObservableObject
|
||||||
|
{
|
||||||
|
public Student Model { get; }
|
||||||
|
public ExamResult? Result { get; }
|
||||||
|
public Niveau? Niveau { get; }
|
||||||
|
public string FullName => Model.FullName;
|
||||||
|
public bool IsCorrected => ExamCoverSheetService.IsCorrected(Result);
|
||||||
|
public string Hint => Result is { Absent: true } ? "abwesend" : "";
|
||||||
|
[ObservableProperty] private bool _isIncluded;
|
||||||
|
|
||||||
|
public ExamCoverStudentChoice(Student model, ExamResult? result, Niveau? niveau = null)
|
||||||
|
{
|
||||||
|
Model = model; Result = result; Niveau = niveau;
|
||||||
|
// Wer gefehlt hat, bekommt kein Deckblatt — lässt sich im Dialog wieder anhaken.
|
||||||
|
_isIncluded = result is not { Absent: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record ReportInterimRunChoice(DateOnly Date, string Occasion, IReadOnlyList<InterimGrade> Grades)
|
||||||
|
{
|
||||||
|
public string Label => $"{Date:dd.MM.yyyy} · {Occasion}";
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
|||||||
private readonly GradingService _grading;
|
private readonly GradingService _grading;
|
||||||
private readonly Exam _exam;
|
private readonly Exam _exam;
|
||||||
private readonly GradingSystem _gradingSystem;
|
private readonly GradingSystem _gradingSystem;
|
||||||
|
private readonly IStudentRepository? _students;
|
||||||
private readonly double _examMaxPoints;
|
private readonly double _examMaxPoints;
|
||||||
private List<ExamResult> _gradedResults = [];
|
private List<ExamResult> _gradedResults = [];
|
||||||
|
|
||||||
@@ -38,19 +39,69 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
|||||||
|
|
||||||
public ObservableCollection<GradeBarItem> GradeDistribution { get; } = [];
|
public ObservableCollection<GradeBarItem> GradeDistribution { get; } = [];
|
||||||
public ObservableCollection<TaskAnalysisItem> TaskAnalysis { get; } = [];
|
public ObservableCollection<TaskAnalysisItem> TaskAnalysis { get; } = [];
|
||||||
|
public ObservableCollection<RepeatComparisonItem> RepeatComparison { get; } = [];
|
||||||
|
public bool HasRepeatComparison => RepeatComparison.Count > 0;
|
||||||
|
public string RepeatComparisonTitle { get; private set; } = "";
|
||||||
|
/// "Wiederholung", "Nachschreibarbeit" bzw. "Förderarbeit" — Beschriftung der Folgearbeit im Vergleich.
|
||||||
|
public string FollowUpLabel { get; private set; } = "Wiederholung";
|
||||||
|
public string FollowUpComparisonHeading => $"Vergleich mit der {FollowUpLabel}";
|
||||||
public ObservableCollection<GradingKeyEntryEditItem> GradingKeyEntries { get; } = [];
|
public ObservableCollection<GradingKeyEntryEditItem> GradingKeyEntries { get; } = [];
|
||||||
|
|
||||||
public ExamEvaluationDialogViewModel(IExamRepository exams, IExamResultRepository results,
|
public ExamEvaluationDialogViewModel(IExamRepository exams, IExamResultRepository results,
|
||||||
GradingService grading, Exam exam, GradingSystem gradingSystem)
|
GradingService grading, Exam exam, GradingSystem gradingSystem,
|
||||||
|
IStudentRepository? students = null)
|
||||||
{
|
{
|
||||||
_exams = exams; _results = results; _grading = grading; _exam = exam;
|
_exams = exams; _results = results; _grading = grading; _exam = exam;
|
||||||
_gradingSystem = gradingSystem;
|
_gradingSystem = gradingSystem; _students = students;
|
||||||
_examMaxPoints = exam.Tasks.Sum(t => t.MaxPoints);
|
_examMaxPoints = ExamScoringService.Maximum(exam.Tasks, ExamVariant.A);
|
||||||
|
|
||||||
foreach (var e in exam.GradingKey.OrderByDescending(e => e.MinPercent))
|
foreach (var e in exam.GradingKey.OrderByDescending(e => e.MinPercent))
|
||||||
AddGradingKeyRowInternal(e.Grade, e.MinPercent);
|
AddGradingKeyRowInternal(e.Grade, e.MinPercent);
|
||||||
|
|
||||||
LoadResults();
|
LoadResults();
|
||||||
|
LoadRepeatComparison(students);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadRepeatComparison(IStudentRepository? students)
|
||||||
|
{
|
||||||
|
RepeatComparison.Clear();
|
||||||
|
RepeatComparisonTitle = "";
|
||||||
|
var original = _exam.RepeatOfExamId is { } originalId ? _exams.GetById(originalId) : _exam;
|
||||||
|
if (original is null) return;
|
||||||
|
var repeat = _exam.RepeatOfExamId is not null ? _exam
|
||||||
|
: _exams.GetByGroup(_exam.GroupId).Where(e => e.RepeatOfExamId == _exam.Id)
|
||||||
|
.OrderBy(e => e.Date).FirstOrDefault();
|
||||||
|
if (repeat is null) return;
|
||||||
|
FollowUpLabel = repeat.IsSupportWork ? "Förderarbeit" : repeat.IsMakeUp ? "Nachschreibarbeit" : "Wiederholung";
|
||||||
|
var rule = repeat.ReplacesMissingGrade() ? "ersetzt fehlende Note" : repeat.RepeatGradeRule switch
|
||||||
|
{
|
||||||
|
RepeatGradeRule.Repeat => "Wiederholung zählt",
|
||||||
|
RepeatGradeRule.Original => "Erste Arbeit zählt",
|
||||||
|
_ => "Bessere zählt",
|
||||||
|
};
|
||||||
|
RepeatComparisonTitle = $"Erste Arbeit: {original.Title} · {FollowUpLabel}: {repeat.Title} · {rule}";
|
||||||
|
var first = _results.GetByExam(original.Id).Where(r => !r.Absent && r.Grade is not null)
|
||||||
|
.ToDictionary(r => r.StudentId);
|
||||||
|
var second = _results.GetByExam(repeat.Id).Where(r => !r.Absent && r.Grade is not null)
|
||||||
|
.ToDictionary(r => r.StudentId);
|
||||||
|
var names = students?.GetByGroup(_exam.GroupId).ToDictionary(s => s.Id, s => s.FullName);
|
||||||
|
foreach (var studentId in first.Keys.Union(second.Keys)
|
||||||
|
.OrderBy(id => names?.GetValueOrDefault(id) ?? id.ToString()))
|
||||||
|
{
|
||||||
|
first.TryGetValue(studentId, out var originalResult);
|
||||||
|
second.TryGetValue(studentId, out var repeatResult);
|
||||||
|
var entries = new List<(Exam Exam, string Grade)>();
|
||||||
|
if (originalResult?.Grade is { } g1) entries.Add((original, g1));
|
||||||
|
if (repeatResult?.Grade is { } g2) entries.Add((repeat, g2));
|
||||||
|
var effective = ExamScoringService.EffectiveGrades(entries, _gradingSystem);
|
||||||
|
RepeatComparison.Add(new RepeatComparisonItem(
|
||||||
|
names?.GetValueOrDefault(studentId) ?? studentId.ToString(),
|
||||||
|
originalResult?.Grade ?? "–", repeatResult?.Grade ?? "–",
|
||||||
|
effective.FirstOrDefault() ?? "–"));
|
||||||
|
}
|
||||||
|
OnPropertyChanged(nameof(HasRepeatComparison));
|
||||||
|
OnPropertyChanged(nameof(RepeatComparisonTitle));
|
||||||
|
OnPropertyChanged(nameof(FollowUpLabel));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void LoadResults()
|
private void LoadResults()
|
||||||
@@ -98,8 +149,11 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
|||||||
foreach (var e in GradingKeyEntries)
|
foreach (var e in GradingKeyEntries)
|
||||||
e.AbsolutePointsDisplay = _examMaxPoints <= 0
|
e.AbsolutePointsDisplay = _examMaxPoints <= 0
|
||||||
? "–"
|
? "–"
|
||||||
: $"ab {(e.MinPercent / 100.0 * _examMaxPoints).ToString("0.##", CultureInfo.InvariantCulture)} " +
|
: _exam.Tasks.Any(t => t.Variant is not null)
|
||||||
$"von {_examMaxPoints.ToString("0.##", CultureInfo.InvariantCulture)} Punkten";
|
? $"A ab {e.MinPercent / 100.0 * _examMaxPoints:0.##} / " +
|
||||||
|
$"B ab {e.MinPercent / 100.0 * ExamScoringService.Maximum(_exam.Tasks, ExamVariant.B):0.##} Punkten"
|
||||||
|
: $"ab {(e.MinPercent / 100.0 * _examMaxPoints).ToString("0.##", CultureInfo.InvariantCulture)} " +
|
||||||
|
$"von {_examMaxPoints.ToString("0.##", CultureInfo.InvariantCulture)} Punkten";
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<GradingKeyEntry> BuildCurrentGradingKey() => GradingKeyEntries
|
private List<GradingKeyEntry> BuildCurrentGradingKey() => GradingKeyEntries
|
||||||
@@ -116,6 +170,12 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
|||||||
GradingKeyValidation = "";
|
GradingKeyValidation = "";
|
||||||
_exam.GradingKey = key;
|
_exam.GradingKey = key;
|
||||||
_exams.Save(_exam);
|
_exams.Save(_exam);
|
||||||
|
var results = _results.GetByExam(_exam.Id);
|
||||||
|
foreach (var result in results.Where(r => !r.Absent))
|
||||||
|
result.Grade = _grading.CalculateGrade(result.TotalPoints,
|
||||||
|
ExamScoringService.Maximum(_exam.Tasks, result.Variant), key);
|
||||||
|
_results.SaveMany(results);
|
||||||
|
LoadRepeatComparison(_students);
|
||||||
GradingKeyStatus = "Notenschlüssel für diese Klausur übernommen.";
|
GradingKeyStatus = "Notenschlüssel für diese Klausur übernommen.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,7 +187,8 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
|||||||
GradingKeyValidation = _grading.ValidateGradingKey(currentKey) ?? "";
|
GradingKeyValidation = _grading.ValidateGradingKey(currentKey) ?? "";
|
||||||
|
|
||||||
var grades = _gradedResults
|
var grades = _gradedResults
|
||||||
.Select(r => _grading.CalculateGrade(r.TotalPoints, _examMaxPoints, currentKey))
|
.Select(r => _grading.CalculateGrade(r.TotalPoints,
|
||||||
|
ExamScoringService.Maximum(_exam.Tasks, r.Variant), currentKey))
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
GradeDistribution.Clear();
|
GradeDistribution.Clear();
|
||||||
@@ -171,14 +232,17 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
|||||||
{
|
{
|
||||||
TaskAnalysis.Clear();
|
TaskAnalysis.Clear();
|
||||||
var tasks = _exam.Tasks.OrderBy(t => t.Nr).ToList();
|
var tasks = _exam.Tasks.OrderBy(t => t.Nr).ToList();
|
||||||
|
var labels = ExamScoringService.TaskLabels(tasks);
|
||||||
for (var i = 0; i < tasks.Count; i++)
|
for (var i = 0; i < tasks.Count; i++)
|
||||||
{
|
{
|
||||||
var task = tasks[i];
|
var task = tasks[i];
|
||||||
var achieved = _gradedResults.Where(r => i < r.Points.Count).Select(r => r.Points[i]).ToList();
|
var achieved = _gradedResults.Where(r => i < r.Points.Count &&
|
||||||
|
ExamScoringService.AppliesTo(task, r.Variant)).Select(r => r.Points[i]).ToList();
|
||||||
var avgPercent = task.MaxPoints <= 0 || achieved.Count == 0
|
var avgPercent = task.MaxPoints <= 0 || achieved.Count == 0
|
||||||
? 0
|
? 0
|
||||||
: achieved.Average() / task.MaxPoints * 100.0;
|
: achieved.Average() / task.MaxPoints * 100.0;
|
||||||
TaskAnalysis.Add(new TaskAnalysisItem(task.Nr, task.Title, avgPercent));
|
var suffix = task.Variant is null ? "" : $" ({task.Variant})";
|
||||||
|
TaskAnalysis.Add(new TaskAnalysisItem(labels[i] + suffix, avgPercent));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -209,8 +273,15 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
|||||||
if (!string.IsNullOrEmpty(BelowThresholdLabel1)) csv.AddRow(BelowThresholdLabel1, BelowThresholdDisplay1);
|
if (!string.IsNullOrEmpty(BelowThresholdLabel1)) csv.AddRow(BelowThresholdLabel1, BelowThresholdDisplay1);
|
||||||
if (!string.IsNullOrEmpty(BelowThresholdLabel2)) csv.AddRow(BelowThresholdLabel2, BelowThresholdDisplay2);
|
if (!string.IsNullOrEmpty(BelowThresholdLabel2)) csv.AddRow(BelowThresholdLabel2, BelowThresholdDisplay2);
|
||||||
csv.AddRow("Bewertet", GradedCount)
|
csv.AddRow("Bewertet", GradedCount)
|
||||||
.AddRow("Abwesend", AbsentCount)
|
.AddRow("Abwesend", AbsentCount);
|
||||||
.AddBlankRow()
|
if (HasRepeatComparison)
|
||||||
|
{
|
||||||
|
csv.AddBlankRow().AddRow("Vergleich", RepeatComparisonTitle)
|
||||||
|
.AddRow("Schüler", "Erste Arbeit", FollowUpLabel, "Zählt");
|
||||||
|
foreach (var item in RepeatComparison)
|
||||||
|
csv.AddRow(item.StudentName, item.OriginalGrade, item.RepeatGrade, item.EffectiveGrade);
|
||||||
|
}
|
||||||
|
csv.AddBlankRow()
|
||||||
.AddRow("Aufgabenanalyse")
|
.AddRow("Aufgabenanalyse")
|
||||||
.AddRow("Aufgabe", "Ø Erfüllungsgrad", "Auffällig schwach");
|
.AddRow("Aufgabe", "Ø Erfüllungsgrad", "Auffällig schwach");
|
||||||
foreach (var t in TaskAnalysis)
|
foreach (var t in TaskAnalysis)
|
||||||
@@ -221,6 +292,9 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
|||||||
|
|
||||||
// ── Notenspiegel-Balken ────────────────────────────────────────────────────
|
// ── Notenspiegel-Balken ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
public record RepeatComparisonItem(string StudentName, string OriginalGrade,
|
||||||
|
string RepeatGrade, string EffectiveGrade);
|
||||||
|
|
||||||
public class GradeBarItem
|
public class GradeBarItem
|
||||||
{
|
{
|
||||||
public string Grade { get; }
|
public string Grade { get; }
|
||||||
@@ -248,9 +322,9 @@ public class TaskAnalysisItem
|
|||||||
public bool IsWeak { get; }
|
public bool IsWeak { get; }
|
||||||
public double BarWidth { get; }
|
public double BarWidth { get; }
|
||||||
|
|
||||||
public TaskAnalysisItem(int nr, string? title, double avgPercent)
|
public TaskAnalysisItem(string label, double avgPercent)
|
||||||
{
|
{
|
||||||
Label = string.IsNullOrWhiteSpace(title) ? $"Aufgabe {nr}" : $"{nr}. {title}";
|
Label = label;
|
||||||
AvgPercent = avgPercent;
|
AvgPercent = avgPercent;
|
||||||
AvgPercentDisplay = $"{avgPercent.ToString("0.#", CultureInfo.InvariantCulture)} %";
|
AvgPercentDisplay = $"{avgPercent.ToString("0.#", CultureInfo.InvariantCulture)} %";
|
||||||
IsWeak = avgPercent < 50.0;
|
IsWeak = avgPercent < 50.0;
|
||||||
|
|||||||
@@ -10,48 +10,126 @@ namespace LehrerApp.Desktop.ViewModels.Groups;
|
|||||||
|
|
||||||
// ── Punkteeingabe & Korrektur (1.4) ──────────────────────────────────────────
|
// ── Punkteeingabe & Korrektur (1.4) ──────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Tastatur-Bewegung im Punkteraster: Next/Previous folgen dem gewählten Korrekturmodus
|
||||||
|
/// (Enter / Umschalt+Enter), die übrigen bewegen sich räumlich (Pfeiltasten).
|
||||||
|
public enum GradingMove { Next, Previous, Up, Down, Left, Right }
|
||||||
|
|
||||||
public partial class ExamGradingDialogViewModel : ObservableObject
|
public partial class ExamGradingDialogViewModel : ObservableObject
|
||||||
{
|
{
|
||||||
private readonly IExamResultRepository _results;
|
private readonly IExamResultRepository _results;
|
||||||
private readonly GradingService _grading;
|
private readonly GradingService _grading;
|
||||||
private readonly Exam _exam;
|
private readonly Exam _exam;
|
||||||
private readonly double _examMaxPoints;
|
private readonly ExamGradingSettingsService? _settings;
|
||||||
|
|
||||||
public string ExamTitle => _exam.Title;
|
public string ExamTitle => _exam.Title;
|
||||||
public string ExamDateLabel => _exam.Date.ToString("dd.MM.yyyy");
|
public string ExamDateLabel => _exam.Date.ToString("dd.MM.yyyy");
|
||||||
public string NiveauLabel => _exam.Niveau.HasValue ? NiveauDisplay.ToName(_exam.Niveau) : "";
|
public string NiveauLabel => _exam.Niveau.HasValue ? NiveauDisplay.ToName(_exam.Niveau) : "";
|
||||||
public List<ExamTask> Tasks { get; }
|
public List<ExamTask> Tasks { get; }
|
||||||
|
public bool HasVariants => Tasks.Any(t => t.Variant is not null);
|
||||||
|
|
||||||
|
/// Spaltenüberschriften — Bonusaufgaben zählen bei der Nummerierung nicht mit.
|
||||||
|
public List<string> TaskHeaders { get; }
|
||||||
|
|
||||||
public ObservableCollection<ExamResultRow> Rows { get; } = [];
|
public ObservableCollection<ExamResultRow> Rows { get; } = [];
|
||||||
|
|
||||||
|
public string[] EntryOrderOptions => ["Schüler für Schüler", "Aufgabe für Aufgabe"];
|
||||||
|
[ObservableProperty] private string _entryOrderName;
|
||||||
|
public GradingEntryOrder EntryOrder =>
|
||||||
|
EntryOrderName == EntryOrderOptions[1] ? GradingEntryOrder.ByTask : GradingEntryOrder.ByStudent;
|
||||||
|
|
||||||
public ExamGradingDialogViewModel(IExamResultRepository results, IStudentRepository students,
|
public ExamGradingDialogViewModel(IExamResultRepository results, IStudentRepository students,
|
||||||
IGroupMembershipRepository memberships, GradingService grading, Exam exam, Guid groupId)
|
IGroupMembershipRepository memberships, GradingService grading, Exam exam, Guid groupId,
|
||||||
|
ExamGradingSettingsService? settings = null)
|
||||||
{
|
{
|
||||||
_results = results; _grading = grading; _exam = exam;
|
_results = results; _grading = grading; _exam = exam; _settings = settings;
|
||||||
Tasks = exam.Tasks.OrderBy(t => t.Nr).ToList();
|
Tasks = exam.Tasks.OrderBy(t => t.Nr).ToList();
|
||||||
_examMaxPoints = Tasks.Sum(t => t.MaxPoints);
|
TaskHeaders = ExamScoringService.TaskLabels(Tasks)
|
||||||
|
.Select((label, i) => (Tasks[i].IsBonus ? "★ " : "") + label
|
||||||
|
+ (Tasks[i].Variant is null ? "" : $" ({Tasks[i].Variant})"))
|
||||||
|
.ToList();
|
||||||
|
_entryOrderName = EntryOrderOptions[
|
||||||
|
settings?.Load().EntryOrder == GradingEntryOrder.ByTask ? 1 : 0];
|
||||||
|
|
||||||
var enrolled = students.GetByGroup(groupId);
|
var enrolled = students.GetByGroup(groupId);
|
||||||
var membershipList = memberships.GetByGroup(groupId);
|
var membershipList = memberships.GetByGroup(groupId);
|
||||||
var existing = results.GetByExam(exam.Id).ToDictionary(r => r.StudentId);
|
var existing = results.GetByExam(exam.Id).ToDictionary(r => r.StudentId);
|
||||||
|
|
||||||
|
var wroteOriginal = ExamParticipantService.WroteOriginal(exam, results.GetByExam);
|
||||||
|
|
||||||
foreach (var s in enrolled.OrderBy(s => s.LastName).ThenBy(s => s.FirstName))
|
foreach (var s in enrolled.OrderBy(s => s.LastName).ThenBy(s => s.FirstName))
|
||||||
{
|
{
|
||||||
var membership = membershipList.FirstOrDefault(e => e.StudentId == s.Id);
|
var membership = membershipList.FirstOrDefault(e => e.StudentId == s.Id);
|
||||||
if (membership is not null && !GroupMembershipService.IsActiveOn(membership, exam.Date)) continue;
|
|
||||||
|
|
||||||
// Niveau-Klausur: nur Schüler mit passendem Niveau zeigen. Klausuren ohne
|
|
||||||
// Niveau-Zuordnung gelten weiterhin für die ganze Gruppe.
|
|
||||||
if (exam.Niveau.HasValue && membership?.Niveau != exam.Niveau) continue;
|
|
||||||
|
|
||||||
existing.TryGetValue(s.Id, out var result);
|
existing.TryGetValue(s.Id, out var result);
|
||||||
var row = new ExamResultRow(s.Id, s.FullName, Tasks, result, _exam.GradingKey, _examMaxPoints, _grading);
|
if (!ExamParticipantService.Includes(exam, membership, result is not null, wroteOriginal.Contains(s.Id)))
|
||||||
|
continue;
|
||||||
|
var row = new ExamResultRow(s.Id, s.FullName, Tasks, result, _exam.GradingKey,
|
||||||
|
ExamScoringService.Maximum(Tasks, ExamVariant.A), _grading);
|
||||||
row.OnChanged = SaveRow;
|
row.OnChanged = SaveRow;
|
||||||
|
row.HasStoredResult = result is not null;
|
||||||
Rows.Add(row);
|
Rows.Add(row);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void SaveRow(ExamResultRow row) => _results.Save(row.ToModel(_exam.Id));
|
/// Eine Zeile, die nur angefahren wurde (Fokus rein, Fokus raus), ist kein Ergebnis: ohne
|
||||||
|
/// Punkte, Abwesenheit oder Kommentar und ohne bereits gespeichertes Ergebnis wird nichts
|
||||||
|
/// angelegt — sonst stünde der Schüler später mit 0 Punkten und Note 6 in der Liste.
|
||||||
|
private void SaveRow(ExamResultRow row)
|
||||||
|
{
|
||||||
|
if (!row.HasStoredResult && !row.HasPoints && !row.Absent && string.IsNullOrWhiteSpace(row.Comment))
|
||||||
|
return;
|
||||||
|
_results.Save(row.ToModel(_exam.Id));
|
||||||
|
row.HasStoredResult = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnEntryOrderNameChanged(string value) =>
|
||||||
|
_settings?.Save(new ExamGradingSettings { EntryOrder = EntryOrder });
|
||||||
|
|
||||||
|
/// Nur Felder, in die tatsächlich etwas eingetragen werden kann: abwesende Schüler und
|
||||||
|
/// Aufgaben der jeweils anderen Fassung werden beim Weiterspringen übersprungen.
|
||||||
|
public bool IsEditable(int rowIdx, int taskIdx) =>
|
||||||
|
rowIdx >= 0 && rowIdx < Rows.Count && taskIdx >= 0 && taskIdx < Tasks.Count
|
||||||
|
&& !Rows[rowIdx].Absent && Rows[rowIdx].Cells[taskIdx].IsApplicable;
|
||||||
|
|
||||||
|
/// Erstes Feld in Korrekturreihenfolge — dort steht der Cursor beim Öffnen des Dialogs.
|
||||||
|
public (int Row, int Task)? FirstCell() =>
|
||||||
|
IsEditable(0, 0) ? (0, 0) : NextCell(0, 0, GradingMove.Next);
|
||||||
|
|
||||||
|
/// Zielfeld für eine Tastatur-Bewegung oder null am Rand. Enter läuft je nach Modus
|
||||||
|
/// zeilen- oder spaltenweise und am Ende einer Zeile/Spalte in die nächste weiter;
|
||||||
|
/// Pfeiltasten bewegen sich nur innerhalb der Zeile bzw. Spalte und halten am Rand an.
|
||||||
|
public (int Row, int Task)? NextCell(int rowIdx, int taskIdx, GradingMove move)
|
||||||
|
{
|
||||||
|
if (move is GradingMove.Next or GradingMove.Previous)
|
||||||
|
{
|
||||||
|
var step = move == GradingMove.Next ? 1 : -1;
|
||||||
|
var byTask = EntryOrder == GradingEntryOrder.ByTask;
|
||||||
|
var total = Rows.Count * Tasks.Count;
|
||||||
|
var pos = byTask ? taskIdx * Rows.Count + rowIdx : rowIdx * Tasks.Count + taskIdx;
|
||||||
|
for (pos += step; pos >= 0 && pos < total; pos += step)
|
||||||
|
{
|
||||||
|
var (r, t) = byTask
|
||||||
|
? (pos % Rows.Count, pos / Rows.Count)
|
||||||
|
: (pos / Tasks.Count, pos % Tasks.Count);
|
||||||
|
if (IsEditable(r, t)) return (r, t);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var (dRow, dTask) = move switch
|
||||||
|
{
|
||||||
|
GradingMove.Up => (-1, 0),
|
||||||
|
GradingMove.Down => (1, 0),
|
||||||
|
GradingMove.Left => (0, -1),
|
||||||
|
_ => (0, 1),
|
||||||
|
};
|
||||||
|
for (int r = rowIdx + dRow, t = taskIdx + dTask;
|
||||||
|
r >= 0 && r < Rows.Count && t >= 0 && t < Tasks.Count;
|
||||||
|
r += dRow, t += dTask)
|
||||||
|
{
|
||||||
|
if (IsEditable(r, t)) return (r, t);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/// Rest als abwesend markieren (Nutzerwunsch): Schüler, die nie nachschreiben, blockieren
|
/// Rest als abwesend markieren (Nutzerwunsch): Schüler, die nie nachschreiben, blockieren
|
||||||
/// sonst dauerhaft den live abgeleiteten Korrekturstatus (ExamPriorityService), weil niemand
|
/// sonst dauerhaft den live abgeleiteten Korrekturstatus (ExamPriorityService), weil niemand
|
||||||
@@ -72,6 +150,7 @@ public partial class ExamResultRow : ObservableObject
|
|||||||
private readonly Guid _resultId;
|
private readonly Guid _resultId;
|
||||||
private readonly List<GradingKeyEntry> _gradingKey;
|
private readonly List<GradingKeyEntry> _gradingKey;
|
||||||
private readonly double _examMaxPoints;
|
private readonly double _examMaxPoints;
|
||||||
|
private readonly List<ExamTask> _tasks;
|
||||||
private readonly GradingService _grading;
|
private readonly GradingService _grading;
|
||||||
|
|
||||||
public Guid StudentId { get; }
|
public Guid StudentId { get; }
|
||||||
@@ -83,24 +162,37 @@ public partial class ExamResultRow : ObservableObject
|
|||||||
[ObservableProperty] private string _comment = "";
|
[ObservableProperty] private string _comment = "";
|
||||||
[ObservableProperty] private double _totalPoints;
|
[ObservableProperty] private double _totalPoints;
|
||||||
[ObservableProperty] private string _gradeDisplay = "";
|
[ObservableProperty] private string _gradeDisplay = "";
|
||||||
|
[ObservableProperty] private string _variantName = "A";
|
||||||
|
public string[] VariantOptions => ["A", "B"];
|
||||||
|
private ExamVariant Variant => VariantName == "B" ? ExamVariant.B : ExamVariant.A;
|
||||||
|
|
||||||
public string TotalPointsDisplay => TotalPoints.ToString("0.##", CultureInfo.InvariantCulture);
|
public string TotalPointsDisplay => TotalPoints.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
public Action<ExamResultRow>? OnChanged { get; set; }
|
public Action<ExamResultRow>? OnChanged { get; set; }
|
||||||
|
|
||||||
|
/// Mindestens eine Aufgabe hat einen eingetragenen Wert (auch 0). Ohne Werte gibt es weder
|
||||||
|
/// Summe noch Note.
|
||||||
|
public bool HasPoints => Cells.Any(c => c.Value is not null);
|
||||||
|
/// Für diesen Schüler liegt in der Datenbank bereits ein Ergebnis dieser Arbeit.
|
||||||
|
public bool HasStoredResult { get; set; }
|
||||||
|
|
||||||
public ExamResultRow(Guid studentId, string name, List<ExamTask> tasks, ExamResult? existing,
|
public ExamResultRow(Guid studentId, string name, List<ExamTask> tasks, ExamResult? existing,
|
||||||
List<GradingKeyEntry> gradingKey, double examMaxPoints, GradingService grading)
|
List<GradingKeyEntry> gradingKey, double examMaxPoints, GradingService grading)
|
||||||
{
|
{
|
||||||
StudentId = studentId; Name = name;
|
StudentId = studentId; Name = name;
|
||||||
_gradingKey = gradingKey; _examMaxPoints = examMaxPoints; _grading = grading;
|
_gradingKey = gradingKey; _examMaxPoints = examMaxPoints; _grading = grading; _tasks = tasks;
|
||||||
_resultId = existing?.Id ?? Guid.NewGuid();
|
_resultId = existing?.Id ?? Guid.NewGuid();
|
||||||
_absent = existing?.Absent ?? false;
|
_absent = existing?.Absent ?? false;
|
||||||
_comment = existing?.Comment ?? "";
|
_comment = existing?.Comment ?? "";
|
||||||
|
_variantName = existing?.Variant.ToString() ?? "A";
|
||||||
|
|
||||||
for (var i = 0; i < tasks.Count; i++)
|
for (var i = 0; i < tasks.Count; i++)
|
||||||
{
|
{
|
||||||
double? pts = existing is not null && i < existing.Points.Count ? existing.Points[i] : null;
|
double? pts = existing is not null && i < existing.Points.Count ? existing.Points[i] : null;
|
||||||
var cell = new PointsCell(tasks[i].MaxPoints, pts);
|
var cell = new PointsCell(tasks[i].MaxPoints, pts)
|
||||||
|
{
|
||||||
|
IsApplicable = ExamScoringService.AppliesTo(tasks[i], Variant),
|
||||||
|
};
|
||||||
cell.OnChanged = () => { RecomputeTotals(); OnChanged?.Invoke(this); };
|
cell.OnChanged = () => { RecomputeTotals(); OnChanged?.Invoke(this); };
|
||||||
Cells.Add(cell);
|
Cells.Add(cell);
|
||||||
}
|
}
|
||||||
@@ -114,12 +206,20 @@ public partial class ExamResultRow : ObservableObject
|
|||||||
}
|
}
|
||||||
|
|
||||||
partial void OnCommentChanged(string value) => OnChanged?.Invoke(this);
|
partial void OnCommentChanged(string value) => OnChanged?.Invoke(this);
|
||||||
|
partial void OnVariantNameChanged(string value)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < Cells.Count; i++)
|
||||||
|
Cells[i].IsApplicable = ExamScoringService.AppliesTo(_tasks[i], Variant);
|
||||||
|
RecomputeTotals();
|
||||||
|
OnChanged?.Invoke(this);
|
||||||
|
}
|
||||||
|
|
||||||
private void RecomputeTotals()
|
private void RecomputeTotals()
|
||||||
{
|
{
|
||||||
TotalPoints = Cells.Sum(c => c.IsInvalid ? 0 : (c.Value ?? 0));
|
TotalPoints = Cells.Sum(c => c.IsApplicable && !c.IsInvalid ? (c.Value ?? 0) : 0);
|
||||||
OnPropertyChanged(nameof(TotalPointsDisplay));
|
OnPropertyChanged(nameof(TotalPointsDisplay));
|
||||||
GradeDisplay = Absent ? "abwesend" : _grading.CalculateGrade(TotalPoints, _examMaxPoints, _gradingKey);
|
GradeDisplay = Absent ? "abwesend" : !HasPoints ? "" : _grading.CalculateGrade(TotalPoints,
|
||||||
|
ExamScoringService.Maximum(_tasks, Variant), _gradingKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ExamResult ToModel(Guid examId) => new()
|
public ExamResult ToModel(Guid examId) => new()
|
||||||
@@ -127,10 +227,11 @@ public partial class ExamResultRow : ObservableObject
|
|||||||
Id = _resultId,
|
Id = _resultId,
|
||||||
ExamId = examId,
|
ExamId = examId,
|
||||||
StudentId = StudentId,
|
StudentId = StudentId,
|
||||||
Points = Cells.Select(c => c.Value ?? 0).ToList(),
|
Points = HasPoints ? Cells.Select(c => c.Value ?? 0).ToList() : [],
|
||||||
TotalPoints = TotalPoints,
|
TotalPoints = TotalPoints,
|
||||||
Grade = Absent ? null : GradeDisplay,
|
Grade = Absent || !HasPoints ? null : GradeDisplay,
|
||||||
Absent = Absent,
|
Absent = Absent,
|
||||||
|
Variant = Variant,
|
||||||
Comment = string.IsNullOrWhiteSpace(Comment) ? null : Comment.Trim(),
|
Comment = string.IsNullOrWhiteSpace(Comment) ? null : Comment.Trim(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -142,6 +243,7 @@ public partial class PointsCell : ObservableObject
|
|||||||
public double MaxPoints { get; }
|
public double MaxPoints { get; }
|
||||||
[ObservableProperty] private double? _value;
|
[ObservableProperty] private double? _value;
|
||||||
[ObservableProperty] private bool _isInvalid;
|
[ObservableProperty] private bool _isInvalid;
|
||||||
|
[ObservableProperty] private bool _isApplicable = true;
|
||||||
|
|
||||||
public Action? OnChanged { get; set; }
|
public Action? OnChanged { get; set; }
|
||||||
|
|
||||||
@@ -154,11 +256,14 @@ public partial class PointsCell : ObservableObject
|
|||||||
|
|
||||||
/// Setzt den Wert; bei Punkten außerhalb 0..Maximalpunkte wird nur rot markiert,
|
/// Setzt den Wert; bei Punkten außerhalb 0..Maximalpunkte wird nur rot markiert,
|
||||||
/// aber nicht gespeichert (1.4.5) — OnChanged (und damit Autosave) wird dann nicht ausgelöst.
|
/// aber nicht gespeichert (1.4.5) — OnChanged (und damit Autosave) wird dann nicht ausgelöst.
|
||||||
|
/// Auch unverändert gelassene Zellen melden sich beim Verlassen des Eingabefelds hier —
|
||||||
|
/// gespeichert wird nur bei einer tatsächlichen Änderung.
|
||||||
public void TrySetValue(double? value)
|
public void TrySetValue(double? value)
|
||||||
{
|
{
|
||||||
|
var changed = Value != value;
|
||||||
Value = value;
|
Value = value;
|
||||||
IsInvalid = IsOutOfRange(value);
|
IsInvalid = IsOutOfRange(value);
|
||||||
if (!IsInvalid) OnChanged?.Invoke();
|
if (!IsInvalid && changed) OnChanged?.Invoke();
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool IsOutOfRange(double? value) =>
|
private bool IsOutOfRange(double? value) =>
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||||||
|
using CommunityToolkit.Mvvm.Input;
|
||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
// ── Datenschutzkonforme Einzelansicht (1.7) ──────────────────────────────────
|
||||||
|
|
||||||
|
/// Zeigt die Leistung genau eines Schülers — zunächst nur den Namen, das Ergebnis erst nach
|
||||||
|
/// "Aufdecken". So kann ein einzelner Schüler nach vorne geholt werden, ohne dass er (oder die
|
||||||
|
/// Klasse über den Beamer) Ergebnisse anderer sieht. Rein lesend.
|
||||||
|
public partial class ExamRevealDialogViewModel : ObservableObject
|
||||||
|
{
|
||||||
|
private readonly Exam _exam;
|
||||||
|
|
||||||
|
public string ExamTitle => _exam.Title;
|
||||||
|
public string ExamDateLabel => _exam.Date.ToString("dd.MM.yyyy");
|
||||||
|
|
||||||
|
public List<ExamRevealStudent> Students { get; } = [];
|
||||||
|
public bool HasStudents => Students.Count > 0;
|
||||||
|
|
||||||
|
[ObservableProperty] private ExamRevealStudent? _selectedStudent;
|
||||||
|
[ObservableProperty] private bool _isRevealed;
|
||||||
|
|
||||||
|
public string PositionLabel => SelectedStudent is null
|
||||||
|
? ""
|
||||||
|
: $"{Students.IndexOf(SelectedStudent) + 1} / {Students.Count}";
|
||||||
|
|
||||||
|
public ExamRevealDialogViewModel(IExamResultRepository results, IStudentRepository students,
|
||||||
|
GradingService grading, Exam exam)
|
||||||
|
{
|
||||||
|
_exam = exam;
|
||||||
|
var tasks = exam.Tasks.OrderBy(t => t.Nr).ToList();
|
||||||
|
var labels = ExamScoringService.TaskLabels(tasks);
|
||||||
|
var enrolled = students.GetByGroup(exam.GroupId).ToDictionary(s => s.Id);
|
||||||
|
|
||||||
|
// Grundlage sind die eingetragenen Ergebnisse: wer keins hat (anderes Niveau, nie
|
||||||
|
// angefasste Zeile), hat hier auch nichts zu sehen. Ausgetretene Schüler mit Ergebnis
|
||||||
|
// bleiben über GetById auffindbar.
|
||||||
|
Students = results.GetByExam(exam.Id)
|
||||||
|
.Select(r => (Result: r, Student: enrolled.GetValueOrDefault(r.StudentId) ?? students.GetById(r.StudentId)))
|
||||||
|
.Where(x => x.Student is not null)
|
||||||
|
.OrderBy(x => x.Student!.LastName).ThenBy(x => x.Student!.FirstName)
|
||||||
|
.Select(x => new ExamRevealStudent(x.Student!, x.Result, tasks, labels, exam.GradingKey, grading))
|
||||||
|
.ToList();
|
||||||
|
_selectedStudent = Students.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Beim Wechsel wird immer wieder zugedeckt — sonst stünde beim Durchblättern sofort das
|
||||||
|
/// Ergebnis des nächsten Schülers offen auf dem Bildschirm.
|
||||||
|
partial void OnSelectedStudentChanged(ExamRevealStudent? value)
|
||||||
|
{
|
||||||
|
IsRevealed = false;
|
||||||
|
OnPropertyChanged(nameof(PositionLabel));
|
||||||
|
PreviousCommand.NotifyCanExecuteChanged();
|
||||||
|
NextCommand.NotifyCanExecuteChanged();
|
||||||
|
RevealCommand.NotifyCanExecuteChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private int SelectedIndex => SelectedStudent is null ? -1 : Students.IndexOf(SelectedStudent);
|
||||||
|
private bool CanGoPrevious() => SelectedIndex > 0;
|
||||||
|
private bool CanGoNext() => SelectedIndex >= 0 && SelectedIndex < Students.Count - 1;
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanGoPrevious))]
|
||||||
|
private void Previous() => SelectedStudent = Students[SelectedIndex - 1];
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanGoNext))]
|
||||||
|
private void Next() => SelectedStudent = Students[SelectedIndex + 1];
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanReveal))]
|
||||||
|
private void Reveal() => IsRevealed = true;
|
||||||
|
private bool CanReveal() => SelectedStudent is not null;
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void Hide() => IsRevealed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ergebnis eines Schülers, fertig aufbereitet für die Einzelansicht.
|
||||||
|
public class ExamRevealStudent
|
||||||
|
{
|
||||||
|
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
|
||||||
|
|
||||||
|
/// "Nachname, Vorname" — für die sortierte Auswahlliste.
|
||||||
|
public string ListName { get; }
|
||||||
|
/// "Vorname Nachname" — für die große Anzeige.
|
||||||
|
public string DisplayName { get; }
|
||||||
|
public bool Absent { get; }
|
||||||
|
public bool HasGrade => !Absent;
|
||||||
|
public string GradeDisplay { get; }
|
||||||
|
public string PointsDisplay { get; }
|
||||||
|
public List<ExamRevealTaskRow> Tasks { get; } = [];
|
||||||
|
|
||||||
|
public ExamRevealStudent(Student student, ExamResult result, IReadOnlyList<ExamTask> orderedTasks,
|
||||||
|
IReadOnlyList<string> taskLabels, List<GradingKeyEntry> gradingKey, GradingService grading)
|
||||||
|
{
|
||||||
|
ListName = student.FullName;
|
||||||
|
DisplayName = $"{student.FirstName} {student.LastName}".Trim();
|
||||||
|
Absent = result.Absent;
|
||||||
|
if (Absent)
|
||||||
|
{
|
||||||
|
GradeDisplay = "abwesend";
|
||||||
|
PointsDisplay = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var maximum = ExamScoringService.Maximum(orderedTasks, result.Variant);
|
||||||
|
GradeDisplay = result.Grade ?? grading.CalculateGrade(result.TotalPoints, maximum, gradingKey);
|
||||||
|
PointsDisplay = $"{Format(result.TotalPoints)} von {Format(maximum)} Punkten";
|
||||||
|
|
||||||
|
// Nur die Aufgaben der geschriebenen Fassung — die der anderen gab es für den Schüler nicht.
|
||||||
|
for (var i = 0; i < orderedTasks.Count; i++)
|
||||||
|
{
|
||||||
|
if (!ExamScoringService.AppliesTo(orderedTasks[i], result.Variant)) continue;
|
||||||
|
var points = i < result.Points.Count ? result.Points[i] : 0;
|
||||||
|
Tasks.Add(new ExamRevealTaskRow(taskLabels[i], Format(points), Format(orderedTasks[i].MaxPoints)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Format(double value) => value.ToString("0.##", German);
|
||||||
|
}
|
||||||
|
|
||||||
|
public record ExamRevealTaskRow(string Label, string Points, string MaxPoints);
|
||||||
@@ -13,6 +13,7 @@ namespace LehrerApp.Desktop.ViewModels.Groups;
|
|||||||
public partial class ExamDialogViewModel : ObservableObject
|
public partial class ExamDialogViewModel : ObservableObject
|
||||||
{
|
{
|
||||||
private readonly IExamRepository _exams;
|
private readonly IExamRepository _exams;
|
||||||
|
private readonly IExamResultRepository? _results;
|
||||||
private readonly ICompetencyDomainRepository _competencyDomains;
|
private readonly ICompetencyDomainRepository _competencyDomains;
|
||||||
private readonly IGradingKeyTemplateRepository _gradingKeyTemplates;
|
private readonly IGradingKeyTemplateRepository _gradingKeyTemplates;
|
||||||
private readonly GradingService _grading;
|
private readonly GradingService _grading;
|
||||||
@@ -41,20 +42,52 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
[ObservableProperty] private string _newTemplateName = "";
|
[ObservableProperty] private string _newTemplateName = "";
|
||||||
[ObservableProperty] private string _gradingKeyValidation = "";
|
[ObservableProperty] private string _gradingKeyValidation = "";
|
||||||
[ObservableProperty] private string _selectedNiveauName = "–";
|
[ObservableProperty] private string _selectedNiveauName = "–";
|
||||||
|
[ObservableProperty] private Exam? _selectedOriginalExam;
|
||||||
|
[ObservableProperty] private string _repeatRuleName = "Bessere zählt";
|
||||||
|
[ObservableProperty] private string _repeatError = "";
|
||||||
|
[ObservableProperty] private string _taskPointsError = "";
|
||||||
|
[ObservableProperty] private string _kindName = ExamKind.Klausur.Label();
|
||||||
|
[ObservableProperty] private string _followUpKindName = WiederholungName;
|
||||||
|
|
||||||
|
private const string WiederholungName = "Wiederholung";
|
||||||
|
private const string NachschreibarbeitName = "Nachschreibarbeit";
|
||||||
|
private const string FoerderarbeitName = "Förderarbeit";
|
||||||
|
// Beim Befüllen aus einer vorhandenen Arbeit darf die Datums-Übernahme das gespeicherte Datum
|
||||||
|
// nicht überschreiben.
|
||||||
|
private bool _initializing = true;
|
||||||
|
|
||||||
public bool IsDifferentiated { get; }
|
public bool IsDifferentiated { get; }
|
||||||
public string[] NiveauOptions => NiveauDisplay.Options;
|
public string[] NiveauOptions => NiveauDisplay.Options;
|
||||||
|
public string[] KindOptions { get; } = Enum.GetValues<ExamKind>().Select(k => k.Label()).ToArray();
|
||||||
|
public string[] RepeatRuleOptions => ["Bessere zählt", "Wiederholung zählt", "Erste Arbeit zählt"];
|
||||||
|
public string[] FollowUpKindOptions { get; } = [WiederholungName, NachschreibarbeitName, FoerderarbeitName];
|
||||||
|
public bool IsMakeUp => FollowUpKindName == NachschreibarbeitName;
|
||||||
|
public bool IsSupportWork => FollowUpKindName == FoerderarbeitName;
|
||||||
|
public bool HasSelectedOriginalExam => SelectedOriginalExam is not null;
|
||||||
|
/// Art und Zählweise sind bei einer verknüpften Folgearbeit festgelegt: sie erbt die Art der
|
||||||
|
/// ersten Arbeit, Nachschreib- und Förderarbeiten ersetzen nur fehlende Noten (keine Regelwahl nötig).
|
||||||
|
public bool CanChooseKind => !HasSelectedOriginalExam;
|
||||||
|
public bool ShowRepeatRule => HasSelectedOriginalExam && FollowUpKindName == WiederholungName;
|
||||||
|
public string LinkedExamLabel => FollowUpKindName switch
|
||||||
|
{
|
||||||
|
NachschreibarbeitName => "Nachschreibarbeit zu (optional)",
|
||||||
|
FoerderarbeitName => "Förderarbeit zu (optional)",
|
||||||
|
_ => "Wiederholung, Nachschreib- oder Förderarbeit zu (optional)",
|
||||||
|
};
|
||||||
|
private ExamKind Kind => Enum.GetValues<ExamKind>().FirstOrDefault(k => k.Label() == KindName);
|
||||||
|
public ObservableCollection<Exam> AvailableOriginalExams { get; } = [];
|
||||||
|
|
||||||
public bool TotalPointsWarning => TotalPoints <= 0;
|
public bool TotalPointsWarning => TotalPoints <= 0;
|
||||||
public string TotalPointsDisplay =>
|
public string TotalPointsDisplay => Tasks.Any(t => t.VariantName != "Beide")
|
||||||
$"{TotalPoints.ToString("0.##", CultureInfo.InvariantCulture)} Punkte gesamt";
|
? $"A: {TotalPoints:0.##} · B: {Tasks.Where(t => !t.IsBonus && t.VariantName != "A").Sum(t => t.MaxPoints):0.##} Punkte (ohne Bonus)"
|
||||||
|
: $"{TotalPoints.ToString("0.##", CultureInfo.InvariantCulture)} Punkte gesamt (ohne Bonus)";
|
||||||
|
|
||||||
public ObservableCollection<ExamTaskEditItem> Tasks { get; } = [];
|
public ObservableCollection<ExamTaskEditItem> Tasks { get; } = [];
|
||||||
public ObservableCollection<GradingKeyEntryEditItem> GradingKeyEntries { get; } = [];
|
public ObservableCollection<GradingKeyEntryEditItem> GradingKeyEntries { get; } = [];
|
||||||
public ObservableCollection<GradingKeyTemplate> AvailableTemplates { get; } = [];
|
public ObservableCollection<GradingKeyTemplate> AvailableTemplates { get; } = [];
|
||||||
|
|
||||||
public Exam? Result { get; private set; }
|
public Exam? Result { get; private set; }
|
||||||
public string DialogTitle => _editingExam is null ? "Neue Klausur anlegen" : "Klausur bearbeiten";
|
public string DialogTitle => _editingExam is null ? "Neue Arbeit anlegen" : "Arbeit bearbeiten";
|
||||||
public string SaveButtonText => _editingExam is null ? "Anlegen" : "Speichern";
|
public string SaveButtonText => _editingExam is null ? "Anlegen" : "Speichern";
|
||||||
|
|
||||||
/// Fach kommt von der Lerngruppe, nicht editierbar (jede Gruppe unterrichtet ein Fach).
|
/// Fach kommt von der Lerngruppe, nicht editierbar (jede Gruppe unterrichtet ein Fach).
|
||||||
@@ -65,9 +98,10 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
IGradingKeyTemplateRepository gradingKeyTemplates, GradingService grading,
|
IGradingKeyTemplateRepository gradingKeyTemplates, GradingService grading,
|
||||||
Guid groupId, Guid? subjectId, int gradeLevel, GradingSystem gradingSystem,
|
Guid groupId, Guid? subjectId, int gradeLevel, GradingSystem gradingSystem,
|
||||||
string defaultSubjectName, bool isDifferentiated, Exam? editingExam, Exam? duplicateSource,
|
string defaultSubjectName, bool isDifferentiated, Exam? editingExam, Exam? duplicateSource,
|
||||||
Guid competencyCatalogVersionId = default)
|
Guid competencyCatalogVersionId = default, IExamResultRepository? results = null)
|
||||||
{
|
{
|
||||||
_exams = exams; _competencyDomains = competencyDomains;
|
_exams = exams; _competencyDomains = competencyDomains;
|
||||||
|
_results = results;
|
||||||
_gradingKeyTemplates = gradingKeyTemplates; _grading = grading;
|
_gradingKeyTemplates = gradingKeyTemplates; _grading = grading;
|
||||||
_groupId = groupId; _subjectId = subjectId; _gradeLevel = gradeLevel;
|
_groupId = groupId; _subjectId = subjectId; _gradeLevel = gradeLevel;
|
||||||
_competencyCatalogVersionId = competencyCatalogVersionId;
|
_competencyCatalogVersionId = competencyCatalogVersionId;
|
||||||
@@ -76,6 +110,13 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
_duplicateSource = duplicateSource;
|
_duplicateSource = duplicateSource;
|
||||||
_subjectName = defaultSubjectName;
|
_subjectName = defaultSubjectName;
|
||||||
IsDifferentiated = isDifferentiated;
|
IsDifferentiated = isDifferentiated;
|
||||||
|
var groupExams = _exams.GetByGroup(groupId);
|
||||||
|
// Mehrere Folgearbeiten je erster Arbeit sind erlaubt (z. B. Nachschreibtermin und
|
||||||
|
// später eine Wiederholung); Folgearbeiten selbst sind keine Bezugsarbeit.
|
||||||
|
foreach (var exam in groupExams
|
||||||
|
.Where(e => e.Id != editingExam?.Id && e.RepeatOfExamId is null)
|
||||||
|
.OrderByDescending(e => e.Date))
|
||||||
|
AvailableOriginalExams.Add(exam);
|
||||||
|
|
||||||
HasCompetencyCatalog = subjectId.HasValue
|
HasCompetencyCatalog = subjectId.HasValue
|
||||||
&& _competencyDomains.GetBySubjectAndGrade(subjectId.Value, gradeLevel, competencyCatalogVersionId).Count > 0;
|
&& _competencyDomains.GetBySubjectAndGrade(subjectId.Value, gradeLevel, competencyCatalogVersionId).Count > 0;
|
||||||
@@ -97,8 +138,22 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
// Beim Duplizieren bewusst kein Niveau übernehmen — meist wird dupliziert, um
|
// Beim Duplizieren bewusst kein Niveau übernehmen — meist wird dupliziert, um
|
||||||
// gerade eine andere Niveau-Variante (E/G/Förder) derselben Klausur anzulegen.
|
// gerade eine andere Niveau-Variante (E/G/Förder) derselben Klausur anzulegen.
|
||||||
SelectedNiveauName = isDuplicate ? "–" : NiveauDisplay.ToName(source.Niveau);
|
SelectedNiveauName = isDuplicate ? "–" : NiveauDisplay.ToName(source.Niveau);
|
||||||
|
KindName = source.Kind.Label();
|
||||||
|
if (!isDuplicate)
|
||||||
|
{
|
||||||
|
SelectedOriginalExam = AvailableOriginalExams.FirstOrDefault(e => e.Id == source.RepeatOfExamId);
|
||||||
|
if (SelectedOriginalExam is not null)
|
||||||
|
FollowUpKindName = source.IsSupportWork ? FoerderarbeitName
|
||||||
|
: source.IsMakeUp ? NachschreibarbeitName : WiederholungName;
|
||||||
|
RepeatRuleName = source.RepeatGradeRule switch
|
||||||
|
{
|
||||||
|
RepeatGradeRule.Repeat => "Wiederholung zählt",
|
||||||
|
RepeatGradeRule.Original => "Erste Arbeit zählt",
|
||||||
|
_ => "Bessere zählt",
|
||||||
|
};
|
||||||
|
}
|
||||||
foreach (var t in source.Tasks.OrderBy(t => t.Nr))
|
foreach (var t in source.Tasks.OrderBy(t => t.Nr))
|
||||||
AddTaskInternal(t.Title, t.MaxPoints, t.Weight, [.. t.Competencies]);
|
AddTaskInternal(t.Title, t.MaxPoints, t.Weight, [.. t.Competencies], t.Variant, t.IsBonus);
|
||||||
UseWeighting = Tasks.Any(t => Math.Abs(t.Weight - 1.0) > 0.0001);
|
UseWeighting = Tasks.Any(t => Math.Abs(t.Weight - 1.0) > 0.0001);
|
||||||
foreach (var e in source.GradingKey.OrderByDescending(e => e.MinPercent))
|
foreach (var e in source.GradingKey.OrderByDescending(e => e.MinPercent))
|
||||||
AddGradingKeyRowInternal(e.Grade, e.MinPercent);
|
AddGradingKeyRowInternal(e.Grade, e.MinPercent);
|
||||||
@@ -113,12 +168,44 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
foreach (var t in Tasks) t.ShowWeight = UseWeighting;
|
foreach (var t in Tasks) t.ShowWeight = UseWeighting;
|
||||||
RecomputeTotals();
|
RecomputeTotals();
|
||||||
UpdateWeekLoadHint();
|
UpdateWeekLoadHint();
|
||||||
|
_initializing = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
partial void OnUseWeightingChanged(bool value)
|
partial void OnUseWeightingChanged(bool value)
|
||||||
{
|
{
|
||||||
foreach (var t in Tasks) t.ShowWeight = value;
|
foreach (var t in Tasks) t.ShowWeight = value;
|
||||||
}
|
}
|
||||||
|
partial void OnSelectedOriginalExamChanged(Exam? value)
|
||||||
|
{
|
||||||
|
if (value is not null) KindName = value.Kind.Label();
|
||||||
|
else FollowUpKindName = WiederholungName;
|
||||||
|
OnPropertyChanged(nameof(HasSelectedOriginalExam));
|
||||||
|
OnPropertyChanged(nameof(CanChooseKind));
|
||||||
|
OnPropertyChanged(nameof(ShowRepeatRule));
|
||||||
|
TakeOverOriginalDateForSupportWork();
|
||||||
|
UpdateWeekLoadHint();
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnFollowUpKindNameChanged(string value)
|
||||||
|
{
|
||||||
|
OnPropertyChanged(nameof(IsMakeUp));
|
||||||
|
OnPropertyChanged(nameof(IsSupportWork));
|
||||||
|
OnPropertyChanged(nameof(ShowRepeatRule));
|
||||||
|
OnPropertyChanged(nameof(LinkedExamLabel));
|
||||||
|
TakeOverOriginalDateForSupportWork();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Eine Förderarbeit wird meist parallel zur ersten Arbeit geschrieben: das Datum der
|
||||||
|
/// ersten Arbeit ist der Vorschlag, bleibt aber änderbar.
|
||||||
|
private void TakeOverOriginalDateForSupportWork()
|
||||||
|
{
|
||||||
|
if (_initializing || !IsSupportWork || SelectedOriginalExam is null) return;
|
||||||
|
DateText = SelectedOriginalExam.Date.ToString("dd.MM.yyyy");
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnKindNameChanged(string value) => UpdateWeekLoadHint();
|
||||||
|
|
||||||
|
[RelayCommand] private void ClearOriginalExam() => SelectedOriginalExam = null;
|
||||||
|
|
||||||
partial void OnDateTextChanged(string value) => UpdateWeekLoadHint();
|
partial void OnDateTextChanged(string value) => UpdateWeekLoadHint();
|
||||||
|
|
||||||
@@ -127,7 +214,8 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
/// ExamWeekLoadService), hier geht es um die eigene Häufung über alle Kurse hinweg.
|
/// ExamWeekLoadService), hier geht es um die eigene Häufung über alle Kurse hinweg.
|
||||||
private void UpdateWeekLoadHint()
|
private void UpdateWeekLoadHint()
|
||||||
{
|
{
|
||||||
if (!DateOnly.TryParseExact(DateText, "dd.MM.yyyy", null, DateTimeStyles.None, out var date))
|
if (!Kind.CountsAsWritten()
|
||||||
|
|| !DateOnly.TryParseExact(DateText, "dd.MM.yyyy", null, DateTimeStyles.None, out var date))
|
||||||
{
|
{
|
||||||
WeekLoadHint = "";
|
WeekLoadHint = "";
|
||||||
return;
|
return;
|
||||||
@@ -148,11 +236,14 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
RecomputeTotals();
|
RecomputeTotals();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void AddTaskInternal(string? title, double maxPoints, double weight, List<CompetencyReference> competencies)
|
private void AddTaskInternal(string? title, double maxPoints, double weight, List<CompetencyReference> competencies,
|
||||||
|
ExamVariant? variant = null, bool isBonus = false)
|
||||||
{
|
{
|
||||||
var item = new ExamTaskEditItem(title, maxPoints, weight, competencies,
|
var item = new ExamTaskEditItem(title, maxPoints, weight, competencies,
|
||||||
BuildCompetencyTagGroups(competencies))
|
BuildCompetencyTagGroups(competencies))
|
||||||
{
|
{
|
||||||
|
VariantName = variant?.ToString() ?? "Beide",
|
||||||
|
IsBonus = isBonus,
|
||||||
OnChanged = RecomputeTotals,
|
OnChanged = RecomputeTotals,
|
||||||
OnRemove = RemoveTask,
|
OnRemove = RemoveTask,
|
||||||
OnMoveUp = MoveTaskUp,
|
OnMoveUp = MoveTaskUp,
|
||||||
@@ -197,11 +288,14 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
private void RenumberTasks()
|
private void RenumberTasks()
|
||||||
{
|
{
|
||||||
for (var i = 0; i < Tasks.Count; i++) Tasks[i].Nr = i + 1;
|
for (var i = 0; i < Tasks.Count; i++) Tasks[i].Nr = i + 1;
|
||||||
|
var numbers = ExamScoringService.TaskNumbers(Tasks.Select(t => t.IsBonus));
|
||||||
|
for (var i = 0; i < Tasks.Count; i++) Tasks[i].DisplayNr = Tasks[i].IsBonus ? "★" : numbers[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
private void RecomputeTotals()
|
private void RecomputeTotals()
|
||||||
{
|
{
|
||||||
TotalPoints = Tasks.Sum(t => t.MaxPoints);
|
RenumberTasks();
|
||||||
|
TotalPoints = Tasks.Where(t => !t.IsBonus && t.VariantName != "B").Sum(t => t.MaxPoints);
|
||||||
OnPropertyChanged(nameof(TotalPointsWarning));
|
OnPropertyChanged(nameof(TotalPointsWarning));
|
||||||
OnPropertyChanged(nameof(TotalPointsDisplay));
|
OnPropertyChanged(nameof(TotalPointsDisplay));
|
||||||
RecomputeGradingKeyAbsolutes();
|
RecomputeGradingKeyAbsolutes();
|
||||||
@@ -214,6 +308,9 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
foreach (var e in GradingKeyEntries)
|
foreach (var e in GradingKeyEntries)
|
||||||
e.AbsolutePointsDisplay = TotalPoints <= 0
|
e.AbsolutePointsDisplay = TotalPoints <= 0
|
||||||
? "–"
|
? "–"
|
||||||
|
: Tasks.Any(t => t.VariantName != "Beide")
|
||||||
|
? $"A ab {e.MinPercent / 100.0 * TotalPoints:0.##} / " +
|
||||||
|
$"B ab {e.MinPercent / 100.0 * Tasks.Where(t => !t.IsBonus && t.VariantName != "A").Sum(t => t.MaxPoints):0.##} Punkten"
|
||||||
: $"ab {(e.MinPercent / 100.0 * TotalPoints).ToString("0.##", CultureInfo.InvariantCulture)} " +
|
: $"ab {(e.MinPercent / 100.0 * TotalPoints).ToString("0.##", CultureInfo.InvariantCulture)} " +
|
||||||
$"von {TotalPoints.ToString("0.##", CultureInfo.InvariantCulture)} Punkten";
|
$"von {TotalPoints.ToString("0.##", CultureInfo.InvariantCulture)} Punkten";
|
||||||
}
|
}
|
||||||
@@ -288,6 +385,7 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
private void Save()
|
private void Save()
|
||||||
{
|
{
|
||||||
TitleError = ""; DateTextError = ""; ReturnedAtTextError = ""; GradingKeyValidation = "";
|
TitleError = ""; DateTextError = ""; ReturnedAtTextError = ""; GradingKeyValidation = "";
|
||||||
|
RepeatError = ""; TaskPointsError = "";
|
||||||
var valid = true;
|
var valid = true;
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(Title)) { TitleError = "Titel erforderlich."; valid = false; }
|
if (string.IsNullOrWhiteSpace(Title)) { TitleError = "Titel erforderlich."; valid = false; }
|
||||||
@@ -313,6 +411,32 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
var gradingKey = BuildGradingKeyEntries();
|
var gradingKey = BuildGradingKeyEntries();
|
||||||
var gradingKeyError = _grading.ValidateGradingKey(gradingKey);
|
var gradingKeyError = _grading.ValidateGradingKey(gradingKey);
|
||||||
if (gradingKeyError is not null) { GradingKeyValidation = gradingKeyError; valid = false; }
|
if (gradingKeyError is not null) { GradingKeyValidation = gradingKeyError; valid = false; }
|
||||||
|
// Datumsprüfung nur bei gültigem Datum — sonst meldet das Datumsfeld den Fehler bereits.
|
||||||
|
// Eine Förderarbeit entsteht parallel zur ersten Arbeit und darf am selben Tag liegen.
|
||||||
|
if (SelectedOriginalExam is not null && DateTextError == "")
|
||||||
|
{
|
||||||
|
if (IsSupportWork)
|
||||||
|
{
|
||||||
|
if (SelectedOriginalExam.Date > date)
|
||||||
|
{
|
||||||
|
RepeatError = "Die Förderarbeit darf nicht vor der ersten Arbeit liegen.";
|
||||||
|
valid = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (SelectedOriginalExam.Date >= date)
|
||||||
|
{
|
||||||
|
RepeatError = IsMakeUp
|
||||||
|
? "Die erste Arbeit muss vor der Nachschreibarbeit liegen."
|
||||||
|
: "Die erste Arbeit muss vor der Wiederholung liegen.";
|
||||||
|
valid = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Tasks.Any(t => t.VariantName != "Beide") &&
|
||||||
|
(TotalPoints <= 0 || Tasks.Where(t => !t.IsBonus && t.VariantName != "A").Sum(t => t.MaxPoints) <= 0))
|
||||||
|
{
|
||||||
|
TaskPointsError = "Fassung A und B brauchen jeweils Grundpunkte.";
|
||||||
|
valid = false;
|
||||||
|
}
|
||||||
|
|
||||||
if (!valid) return;
|
if (!valid) return;
|
||||||
|
|
||||||
@@ -325,12 +449,34 @@ public partial class ExamDialogViewModel : ObservableObject
|
|||||||
Result.Niveau = NiveauDisplay.FromName(SelectedNiveauName);
|
Result.Niveau = NiveauDisplay.FromName(SelectedNiveauName);
|
||||||
Result.Tasks = Tasks.Select(t => t.ToModel()).ToList();
|
Result.Tasks = Tasks.Select(t => t.ToModel()).ToList();
|
||||||
Result.GradingKey = gradingKey;
|
Result.GradingKey = gradingKey;
|
||||||
|
Result.RepeatOfExamId = SelectedOriginalExam?.Id;
|
||||||
|
Result.Kind = SelectedOriginalExam?.Kind ?? Kind;
|
||||||
|
Result.IsMakeUp = IsMakeUp && SelectedOriginalExam is not null;
|
||||||
|
Result.IsSupportWork = IsSupportWork && SelectedOriginalExam is not null;
|
||||||
|
Result.RepeatGradeRule = RepeatRuleName switch
|
||||||
|
{
|
||||||
|
"Wiederholung zählt" => RepeatGradeRule.Repeat,
|
||||||
|
"Erste Arbeit zählt" => RepeatGradeRule.Original,
|
||||||
|
_ => RepeatGradeRule.Better,
|
||||||
|
};
|
||||||
// Parallelkurse (gleiche Arbeit, mehrere Kurse): beim Duplizieren verknüpfen, damit die
|
// Parallelkurse (gleiche Arbeit, mehrere Kurse): beim Duplizieren verknüpfen, damit die
|
||||||
// Klausuren-Hauptseite zwischen ihnen umschalten kann. Der Anker ist die Id der zuerst
|
// Klausuren-Hauptseite zwischen ihnen umschalten kann. Der Anker ist die Id der zuerst
|
||||||
// angelegten Klausur der Kette — schon verknüpfte Quellen geben ihren Anker weiter.
|
// angelegten Klausur der Kette — schon verknüpfte Quellen geben ihren Anker weiter.
|
||||||
if (_duplicateSource is not null)
|
if (_duplicateSource is not null)
|
||||||
Result.SharedExamGroupId = _duplicateSource.SharedExamGroupId ?? _duplicateSource.Id;
|
Result.SharedExamGroupId = _duplicateSource.SharedExamGroupId ?? _duplicateSource.Id;
|
||||||
_exams.Save(Result);
|
_exams.Save(Result);
|
||||||
|
if (_editingExam is not null && _results is not null)
|
||||||
|
{
|
||||||
|
var tasks = Result.Tasks.OrderBy(t => t.Nr).ToList();
|
||||||
|
var existingResults = _results.GetByExam(Result.Id);
|
||||||
|
foreach (var result in existingResults.Where(r => !r.Absent))
|
||||||
|
{
|
||||||
|
result.TotalPoints = ExamScoringService.Achieved(tasks, result.Points, result.Variant);
|
||||||
|
result.Grade = _grading.CalculateGrade(result.TotalPoints,
|
||||||
|
ExamScoringService.Maximum(tasks, result.Variant), gradingKey);
|
||||||
|
}
|
||||||
|
_results.SaveMany(existingResults);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -356,11 +502,16 @@ public partial class GradingKeyEntryEditItem : ObservableObject
|
|||||||
public partial class ExamTaskEditItem : ObservableObject
|
public partial class ExamTaskEditItem : ObservableObject
|
||||||
{
|
{
|
||||||
[ObservableProperty] private int _nr;
|
[ObservableProperty] private int _nr;
|
||||||
|
/// Angezeigte Nummer — Bonusaufgaben zählen nicht mit (siehe ExamScoringService.TaskNumbers).
|
||||||
|
[ObservableProperty] private string _displayNr = "";
|
||||||
[ObservableProperty] private string _title = "";
|
[ObservableProperty] private string _title = "";
|
||||||
[ObservableProperty] private double _maxPoints;
|
[ObservableProperty] private double _maxPoints;
|
||||||
[ObservableProperty] private double _weight = 1.0;
|
[ObservableProperty] private double _weight = 1.0;
|
||||||
[ObservableProperty] private bool _isCompetencyPanelOpen;
|
[ObservableProperty] private bool _isCompetencyPanelOpen;
|
||||||
[ObservableProperty] private bool _showWeight;
|
[ObservableProperty] private bool _showWeight;
|
||||||
|
[ObservableProperty] private string _variantName = "Beide";
|
||||||
|
[ObservableProperty] private bool _isBonus;
|
||||||
|
public string[] VariantOptions => ["Beide", "A", "B"];
|
||||||
|
|
||||||
public List<CompetencyReference> Competencies { get; }
|
public List<CompetencyReference> Competencies { get; }
|
||||||
public ObservableCollection<CompetencyTagGroup> CompetencyTagGroups { get; } = [];
|
public ObservableCollection<CompetencyTagGroup> CompetencyTagGroups { get; } = [];
|
||||||
@@ -409,6 +560,8 @@ public partial class ExamTaskEditItem : ObservableObject
|
|||||||
[RelayCommand] private void MoveDown() => OnMoveDown?.Invoke(this);
|
[RelayCommand] private void MoveDown() => OnMoveDown?.Invoke(this);
|
||||||
|
|
||||||
partial void OnMaxPointsChanged(double value) => OnChanged?.Invoke();
|
partial void OnMaxPointsChanged(double value) => OnChanged?.Invoke();
|
||||||
|
partial void OnVariantNameChanged(string value) => OnChanged?.Invoke();
|
||||||
|
partial void OnIsBonusChanged(bool value) => OnChanged?.Invoke();
|
||||||
|
|
||||||
public ExamTask ToModel() => new()
|
public ExamTask ToModel() => new()
|
||||||
{
|
{
|
||||||
@@ -416,6 +569,8 @@ public partial class ExamTaskEditItem : ObservableObject
|
|||||||
Title = string.IsNullOrWhiteSpace(Title) ? null : Title.Trim(),
|
Title = string.IsNullOrWhiteSpace(Title) ? null : Title.Trim(),
|
||||||
MaxPoints = MaxPoints,
|
MaxPoints = MaxPoints,
|
||||||
Weight = Weight,
|
Weight = Weight,
|
||||||
|
Variant = VariantName switch { "A" => ExamVariant.A, "B" => ExamVariant.B, _ => null },
|
||||||
|
IsBonus = IsBonus,
|
||||||
Competencies = Competencies,
|
Competencies = Competencies,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -54,12 +54,16 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
|||||||
public Func<GradeOverviewRow, Task>? OnManageStudentGrades { get; set; }
|
public Func<GradeOverviewRow, Task>? OnManageStudentGrades { get; set; }
|
||||||
public Func<Task>? OnCollectiveGrade { get; set; }
|
public Func<Task>? OnCollectiveGrade { get; set; }
|
||||||
public Func<Task>? OnReportGrades { get; set; }
|
public Func<Task>? OnReportGrades { get; set; }
|
||||||
|
public Func<Guid?, Task>? OnInterimGrades { get; set; }
|
||||||
public Func<GradeOverviewRow, Task>? OnShowPerformanceOverview { get; set; }
|
public Func<GradeOverviewRow, Task>? OnShowPerformanceOverview { get; set; }
|
||||||
|
|
||||||
|
private readonly IInterimGradeRepository _interimGrades;
|
||||||
|
|
||||||
public GradeOverviewTabViewModel(IGradeRepository grades, IExamRepository exams,
|
public GradeOverviewTabViewModel(IGradeRepository grades, IExamRepository exams,
|
||||||
IExamResultRepository results, IStudentRepository students,
|
IExamResultRepository results, IStudentRepository students,
|
||||||
IGroupMembershipRepository memberships, GradingService grading)
|
IGroupMembershipRepository memberships, IInterimGradeRepository interimGrades, GradingService grading)
|
||||||
{
|
{
|
||||||
|
_interimGrades = interimGrades;
|
||||||
_grades = grades; _exams = exams; _results = results;
|
_grades = grades; _exams = exams; _results = results;
|
||||||
_students = students; _memberships = memberships; _grading = grading;
|
_students = students; _memberships = memberships; _grading = grading;
|
||||||
_selectedPeriod = PeriodOptions[0];
|
_selectedPeriod = PeriodOptions[0];
|
||||||
@@ -131,6 +135,15 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
|||||||
await OnReportGrades();
|
await OnReportGrades();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Zwischenstand notieren: mit markiertem Schüler nur für diesen vorausgewählt, sonst für alle.
|
||||||
|
[RelayCommand]
|
||||||
|
private async Task InterimGrades()
|
||||||
|
{
|
||||||
|
if (OnInterimGrades is null) return;
|
||||||
|
await OnInterimGrades(SelectedRow?.StudentId);
|
||||||
|
Recompute();
|
||||||
|
}
|
||||||
|
|
||||||
private void Recompute()
|
private void Recompute()
|
||||||
{
|
{
|
||||||
var period = SelectedPeriod.Period;
|
var period = SelectedPeriod.Period;
|
||||||
@@ -170,6 +183,15 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
|||||||
Columns.Add(new GradeOverviewColumnDef(header));
|
Columns.Add(new GradeOverviewColumnDef(header));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Zwischenstände (2.7.5): je Durchgang eine Spalte, grau dargestellt. Sie sind vorläufig
|
||||||
|
// und fließen bewusst nicht in "Gesamt" ein.
|
||||||
|
var interimGrades = _interimGrades.GetByGroup(_groupId)
|
||||||
|
.Where(g => g.Date >= periodFrom && g.Date <= periodTo)
|
||||||
|
.ToList();
|
||||||
|
var interimRuns = interimGrades.Select(g => (g.Date, g.Occasion)).Distinct().OrderBy(r => r.Date).ToList();
|
||||||
|
foreach (var run in interimRuns)
|
||||||
|
Columns.Add(new GradeOverviewColumnDef($"Zwischenstand {run.Date:dd.MM.} {run.Occasion}", isInterim: true));
|
||||||
|
|
||||||
Rows.Clear();
|
Rows.Clear();
|
||||||
foreach (var student in students)
|
foreach (var student in students)
|
||||||
{
|
{
|
||||||
@@ -178,6 +200,7 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
|||||||
|
|
||||||
var cells = new List<string>();
|
var cells = new List<string>();
|
||||||
var numeric = new List<(string Grade, double Weight)>();
|
var numeric = new List<(string Grade, double Weight)>();
|
||||||
|
var examEntries = new List<(Exam Exam, string Grade)>();
|
||||||
|
|
||||||
foreach (var exam in exams)
|
foreach (var exam in exams)
|
||||||
{
|
{
|
||||||
@@ -189,8 +212,10 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
|||||||
if (result.Absent) { cells.Add("abwesend"); continue; }
|
if (result.Absent) { cells.Add("abwesend"); continue; }
|
||||||
var display = FormatValue(result.Grade);
|
var display = FormatValue(result.Grade);
|
||||||
cells.Add(display);
|
cells.Add(display);
|
||||||
if (result.Grade is not null) numeric.Add((result.Grade, 1.0));
|
if (result.Grade is not null) examEntries.Add((exam, result.Grade));
|
||||||
}
|
}
|
||||||
|
var (writtenGrades, testGrades) = ExamScoringService.EffectiveGradesByKind(examEntries, _gradingSystem);
|
||||||
|
numeric.AddRange(writtenGrades.Concat(testGrades).Select(grade => (Grade: grade, Weight: 1.0)));
|
||||||
|
|
||||||
foreach (var key in gradeColumnKeys)
|
foreach (var key in gradeColumnKeys)
|
||||||
{
|
{
|
||||||
@@ -204,6 +229,10 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
|||||||
numeric.Add((grade.Value, grade.Weight));
|
numeric.Add((grade.Value, grade.Weight));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
foreach (var run in interimRuns)
|
||||||
|
cells.Add(FormatValue(interimGrades.FirstOrDefault(g =>
|
||||||
|
g.StudentId == student.Id && g.Date == run.Date && g.Occasion == run.Occasion)?.OverallValue));
|
||||||
|
|
||||||
var total = numeric.Count == 0 ? (double?)null : _grading.WeightedAverage(numeric);
|
var total = numeric.Count == 0 ? (double?)null : _grading.WeightedAverage(numeric);
|
||||||
var totalDisplay = total is null ? "–" : total.Value.ToString("0.00", CultureInfo.InvariantCulture);
|
var totalDisplay = total is null ? "–" : total.Value.ToString("0.00", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
@@ -233,9 +262,11 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class GradeOverviewColumnDef(string header)
|
public class GradeOverviewColumnDef(string header, bool isInterim = false)
|
||||||
{
|
{
|
||||||
public string Header { get; } = header;
|
public string Header { get; } = header;
|
||||||
|
/// Vorläufige Note eines Zwischenstand-Durchgangs — grau, nicht in "Gesamt", nicht im PDF.
|
||||||
|
public bool IsInterim { get; } = isInterim;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class GradeOverviewRow(Guid studentId, string name, List<string> cells, string totalDisplay, double? totalSortValue)
|
public class GradeOverviewRow(Guid studentId, string name, List<string> cells, string totalDisplay, double? totalSortValue)
|
||||||
|
|||||||
@@ -206,11 +206,15 @@ public partial class GroupOverviewViewModel : ObservableObject
|
|||||||
|
|
||||||
private (double Average, int Count)? ComputeExamAverage(Guid groupId)
|
private (double Average, int Count)? ComputeExamAverage(Guid groupId)
|
||||||
{
|
{
|
||||||
|
var system = _groups.GetById(groupId)?.GradingSystem ?? GradingSystem.Grades1To6;
|
||||||
var grades = _exams.GetByGroup(groupId)
|
var grades = _exams.GetByGroup(groupId)
|
||||||
.SelectMany(e => _examResults.GetByExam(e.Id))
|
.SelectMany(e => _examResults.GetByExam(e.Id)
|
||||||
.Where(r => !r.Absent && !string.IsNullOrWhiteSpace(r.Grade))
|
.Where(r => !r.Absent && !string.IsNullOrWhiteSpace(r.Grade))
|
||||||
.Select(r => (Grade: r.Grade!, Weight: 1.0))
|
.Select(r => (r.StudentId, Exam: e, Grade: r.Grade!)))
|
||||||
.ToList();
|
.GroupBy(x => x.StudentId)
|
||||||
|
.SelectMany(g => ExamScoringService.EffectiveGrades(
|
||||||
|
g.Where(x => x.Exam.Kind.CountsAsWritten()).Select(x => (x.Exam, x.Grade)), system))
|
||||||
|
.Select(grade => (Grade: grade, Weight: 1.0)).ToList();
|
||||||
return grades.Count == 0 ? null : (_grading.WeightedAverage(grades), grades.Count);
|
return grades.Count == 0 ? null : (_grading.WeightedAverage(grades), grades.Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -292,6 +296,7 @@ public partial class GroupOverviewViewModel : ObservableObject
|
|||||||
{
|
{
|
||||||
DraftDocumentationCount = _students.GetByGroup(_groupId)
|
DraftDocumentationCount = _students.GetByGroup(_groupId)
|
||||||
.SelectMany(s => _documentation.GetByStudent(s.Id))
|
.SelectMany(s => _documentation.GetByStudent(s.Id))
|
||||||
|
.DistinctBy(d => d.Id)
|
||||||
.Count(d => d.IsDraft && (d.GroupId is null || d.GroupId == _groupId));
|
.Count(d => d.IsDraft && (d.GroupId is null || d.GroupId == _groupId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -198,6 +198,8 @@ public partial class GroupDetailViewModel : ObservableObject
|
|||||||
// bevor LoadGroup() läuft (siehe MainWindowViewModel.NavigateToGroupDetail), Group ist dann
|
// bevor LoadGroup() läuft (siehe MainWindowViewModel.NavigateToGroupDetail), Group ist dann
|
||||||
// kurzzeitig null — ein verschachtelter Pfad würde dafür jedes Mal einen Binding-Fehler loggen.
|
// kurzzeitig null — ein verschachtelter Pfad würde dafür jedes Mal einen Binding-Fehler loggen.
|
||||||
public bool IsDifferentiated => Group?.IsDifferentiated ?? false;
|
public bool IsDifferentiated => Group?.IsDifferentiated ?? false;
|
||||||
|
/// In differenzierten Gruppen übernimmt das Förderniveau die Rolle der Markierung.
|
||||||
|
public bool ShowSupportColumn => !IsDifferentiated;
|
||||||
public bool IsReadOnly => Group is { IsActive: false };
|
public bool IsReadOnly => Group is { IsActive: false };
|
||||||
public bool IsEditable => Group is { IsActive: true };
|
public bool IsEditable => Group is { IsActive: true };
|
||||||
public string SubjectName { get; private set; } = "";
|
public string SubjectName { get; private set; } = "";
|
||||||
@@ -205,6 +207,7 @@ public partial class GroupDetailViewModel : ObservableObject
|
|||||||
partial void OnGroupChanged(LearningGroup? value)
|
partial void OnGroupChanged(LearningGroup? value)
|
||||||
{
|
{
|
||||||
OnPropertyChanged(nameof(IsDifferentiated));
|
OnPropertyChanged(nameof(IsDifferentiated));
|
||||||
|
OnPropertyChanged(nameof(ShowSupportColumn));
|
||||||
OnPropertyChanged(nameof(IsReadOnly));
|
OnPropertyChanged(nameof(IsReadOnly));
|
||||||
OnPropertyChanged(nameof(IsEditable));
|
OnPropertyChanged(nameof(IsEditable));
|
||||||
NotifyWriteCommands();
|
NotifyWriteCommands();
|
||||||
@@ -234,6 +237,8 @@ public partial class GroupDetailViewModel : ObservableObject
|
|||||||
public Func<ExamSummary, Task<bool>>? OnConfirmDeleteExam { get; set; }
|
public Func<ExamSummary, Task<bool>>? OnConfirmDeleteExam { get; set; }
|
||||||
public Func<Exam, Task>? OnGradeExam { get; set; }
|
public Func<Exam, Task>? OnGradeExam { get; set; }
|
||||||
public Func<Exam, Task>? OnEvaluateExam { get; set; }
|
public Func<Exam, Task>? OnEvaluateExam { get; set; }
|
||||||
|
public Func<Exam, Task>? OnRevealExam { get; set; }
|
||||||
|
public Func<Exam, Task>? OnExamCoverSheets { get; set; }
|
||||||
public Func<Task<bool>>? OnConfirmReactivate { get; set; }
|
public Func<Task<bool>>? OnConfirmReactivate { get; set; }
|
||||||
|
|
||||||
public GroupDetailViewModel(IGroupRepository groups, IStudentRepository students,
|
public GroupDetailViewModel(IGroupRepository groups, IStudentRepository students,
|
||||||
@@ -322,6 +327,7 @@ public partial class GroupDetailViewModel : ObservableObject
|
|||||||
var membership = _memberships.GetByStudentAndGroup(summary.Id, Group.Id);
|
var membership = _memberships.GetByStudentAndGroup(summary.Id, Group.Id);
|
||||||
if (membership is null) return;
|
if (membership is null) return;
|
||||||
membership.Niveau = summary.Niveau;
|
membership.Niveau = summary.Niveau;
|
||||||
|
membership.IsSupportStudent = summary.IsSupportStudent;
|
||||||
_memberships.Save(membership);
|
_memberships.Save(membership);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -411,6 +417,24 @@ public partial class GroupDetailViewModel : ObservableObject
|
|||||||
await OnEvaluateExam(exam);
|
await OnEvaluateExam(exam);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanEditSelectedExam))]
|
||||||
|
private async Task RevealExam()
|
||||||
|
{
|
||||||
|
if (SelectedExam is null || OnRevealExam is null) return;
|
||||||
|
var exam = _exams.GetById(SelectedExam.Id);
|
||||||
|
if (exam is null) return;
|
||||||
|
await OnRevealExam(exam);
|
||||||
|
}
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanEditSelectedExam))]
|
||||||
|
private async Task ExamCoverSheets()
|
||||||
|
{
|
||||||
|
if (SelectedExam is null || OnExamCoverSheets is null) return;
|
||||||
|
var exam = _exams.GetById(SelectedExam.Id);
|
||||||
|
if (exam is null) return;
|
||||||
|
await OnExamCoverSheets(exam);
|
||||||
|
}
|
||||||
|
|
||||||
[RelayCommand(CanExecute = nameof(CanEditSelectedExam))]
|
[RelayCommand(CanExecute = nameof(CanEditSelectedExam))]
|
||||||
private async Task DuplicateExam()
|
private async Task DuplicateExam()
|
||||||
{
|
{
|
||||||
@@ -427,6 +451,11 @@ public partial class GroupDetailViewModel : ObservableObject
|
|||||||
if (SelectedExam is null || OnConfirmDeleteExam is null) return;
|
if (SelectedExam is null || OnConfirmDeleteExam is null) return;
|
||||||
var selected = SelectedExam;
|
var selected = SelectedExam;
|
||||||
if (!await OnConfirmDeleteExam(selected)) return;
|
if (!await OnConfirmDeleteExam(selected)) return;
|
||||||
|
foreach (var repeat in _exams.GetByGroup(Group!.Id).Where(e => e.RepeatOfExamId == selected.Id))
|
||||||
|
{
|
||||||
|
repeat.RepeatOfExamId = null;
|
||||||
|
_exams.Save(repeat);
|
||||||
|
}
|
||||||
_exams.Delete(selected.Id);
|
_exams.Delete(selected.Id);
|
||||||
SelectedExam = null;
|
SelectedExam = null;
|
||||||
ReloadExams();
|
ReloadExams();
|
||||||
@@ -480,6 +509,8 @@ public partial class GroupDetailViewModel : ObservableObject
|
|||||||
EditExamCommand.NotifyCanExecuteChanged();
|
EditExamCommand.NotifyCanExecuteChanged();
|
||||||
GradeExamCommand.NotifyCanExecuteChanged();
|
GradeExamCommand.NotifyCanExecuteChanged();
|
||||||
EvaluateExamCommand.NotifyCanExecuteChanged();
|
EvaluateExamCommand.NotifyCanExecuteChanged();
|
||||||
|
RevealExamCommand.NotifyCanExecuteChanged();
|
||||||
|
ExamCoverSheetsCommand.NotifyCanExecuteChanged();
|
||||||
DuplicateExamCommand.NotifyCanExecuteChanged();
|
DuplicateExamCommand.NotifyCanExecuteChanged();
|
||||||
DeleteExamCommand.NotifyCanExecuteChanged();
|
DeleteExamCommand.NotifyCanExecuteChanged();
|
||||||
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
|
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
|
||||||
@@ -509,6 +540,8 @@ public partial class GroupDetailViewModel : ObservableObject
|
|||||||
EditExamCommand.NotifyCanExecuteChanged();
|
EditExamCommand.NotifyCanExecuteChanged();
|
||||||
GradeExamCommand.NotifyCanExecuteChanged();
|
GradeExamCommand.NotifyCanExecuteChanged();
|
||||||
EvaluateExamCommand.NotifyCanExecuteChanged();
|
EvaluateExamCommand.NotifyCanExecuteChanged();
|
||||||
|
RevealExamCommand.NotifyCanExecuteChanged();
|
||||||
|
ExamCoverSheetsCommand.NotifyCanExecuteChanged();
|
||||||
DuplicateExamCommand.NotifyCanExecuteChanged();
|
DuplicateExamCommand.NotifyCanExecuteChanged();
|
||||||
DeleteExamCommand.NotifyCanExecuteChanged();
|
DeleteExamCommand.NotifyCanExecuteChanged();
|
||||||
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
|
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
|
||||||
@@ -558,6 +591,7 @@ public partial class StudentSummary : ObservableObject
|
|||||||
public string AvatarTooltip { get; }
|
public string AvatarTooltip { get; }
|
||||||
|
|
||||||
[ObservableProperty] private Niveau? _niveau;
|
[ObservableProperty] private Niveau? _niveau;
|
||||||
|
[ObservableProperty] private bool _isSupportStudent;
|
||||||
|
|
||||||
public string NiveauName
|
public string NiveauName
|
||||||
{
|
{
|
||||||
@@ -583,8 +617,11 @@ public partial class StudentSummary : ObservableObject
|
|||||||
? IsFormer ? $"Ausgetreten am {exitDate:dd.MM.yyyy}" : $"Austritt am {exitDate:dd.MM.yyyy}"
|
? IsFormer ? $"Ausgetreten am {exitDate:dd.MM.yyyy}" : $"Austritt am {exitDate:dd.MM.yyyy}"
|
||||||
: "Aktiv";
|
: "Aktiv";
|
||||||
_niveau = membership?.Niveau;
|
_niveau = membership?.Niveau;
|
||||||
|
_isSupportStudent = membership?.IsSupportStudent ?? false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
partial void OnIsSupportStudentChanged(bool value) => OnChanged?.Invoke(this);
|
||||||
|
|
||||||
partial void OnNiveauChanged(Niveau? value)
|
partial void OnNiveauChanged(Niveau? value)
|
||||||
{
|
{
|
||||||
OnPropertyChanged(nameof(NiveauName));
|
OnPropertyChanged(nameof(NiveauName));
|
||||||
@@ -618,12 +655,23 @@ public class ExamSummary
|
|||||||
public string StatusColorHex { get; }
|
public string StatusColorHex { get; }
|
||||||
public string ReturnedAtDisplay { get; }
|
public string ReturnedAtDisplay { get; }
|
||||||
public string NiveauLabel { get; }
|
public string NiveauLabel { get; }
|
||||||
|
public string TypeLabel { get; }
|
||||||
|
|
||||||
public ExamSummary(Core.Models.Exam e)
|
public ExamSummary(Core.Models.Exam e)
|
||||||
{
|
{
|
||||||
Id = e.Id; Title = e.Title; Date = e.Date.ToString("dd.MM.yyyy"); Status = e.Status;
|
Id = e.Id; Title = e.Title; Date = e.Date.ToString("dd.MM.yyyy"); Status = e.Status;
|
||||||
ReturnedAtDisplay = e.ReturnedAt?.ToString("dd.MM.yyyy") ?? "";
|
ReturnedAtDisplay = e.ReturnedAt?.ToString("dd.MM.yyyy") ?? "";
|
||||||
NiveauLabel = e.Niveau.HasValue ? NiveauDisplay.ToName(e.Niveau) : "alle";
|
NiveauLabel = e.Niveau.HasValue ? NiveauDisplay.ToName(e.Niveau) : "alle";
|
||||||
|
var hasVariants = e.Tasks.Any(t => t.Variant is not null);
|
||||||
|
var followUp = e.RepeatOfExamId is null ? null
|
||||||
|
: e.IsSupportWork ? (hasVariants ? "Förder · A/B" : "Förderarbeit")
|
||||||
|
: e.IsMakeUp ? (hasVariants ? "Nachschr. · A/B" : "Nachschreiben")
|
||||||
|
: hasVariants ? "Wdh. · A/B" : "Wiederholung";
|
||||||
|
// Folgearbeiten behalten ihre Art im Hintergrund (sie erben sie), die Spalte nennt nur
|
||||||
|
// die Beziehung; bei eigenständigen Arbeiten steht die Art selbst.
|
||||||
|
TypeLabel = followUp ?? (e.Kind == ExamKind.Klausur
|
||||||
|
? (hasVariants ? "A/B" : "Klausur")
|
||||||
|
: hasVariants ? $"{e.Kind.Label()} · A/B" : e.Kind.Label());
|
||||||
StatusLabel = e.Status switch
|
StatusLabel = e.Status switch
|
||||||
{
|
{
|
||||||
ExamStatus.Planned => "Geplant",
|
ExamStatus.Planned => "Geplant",
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
/// <param name="RunningParticipation">Notenvorschlag des am Stichtag laufenden
|
||||||
|
/// Mitarbeits-Abschnitts, der in <paramref name="Result"/> bereits eingerechnet ist.</param>
|
||||||
|
public sealed record InterimResult(ParticipationPeriod Period, ReportGradeResult Result, string? RunningParticipation);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Vorläufige Halbjahresnote zu einem Stichtag (Zwischenstand, 2.7.5). Anders als die
|
||||||
|
/// Zeugnisnote zählt hier der laufende Mitarbeits-Abschnitt mit seinem Vorschlag mit — sonst
|
||||||
|
/// bestünde ein Zwischenstand früh im Halbjahr nur aus dem Schriftlichen.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class InterimGradeCalculator(ReportGradeCalculator calculator, ParticipationTimelineBuilder timeline,
|
||||||
|
IReadOnlyList<ParticipationSection> sections)
|
||||||
|
{
|
||||||
|
/// Das Halbjahr, zu dem ein Stichtag gehört.
|
||||||
|
public ParticipationPeriod HalfOf(DateOnly date) =>
|
||||||
|
date <= calculator.Range(ParticipationPeriod.H1).To ? ParticipationPeriod.H1 : ParticipationPeriod.H2;
|
||||||
|
|
||||||
|
public InterimResult Calculate(Guid studentId, DateOnly asOf, RoundingRule rounding)
|
||||||
|
{
|
||||||
|
var period = HalfOf(asOf);
|
||||||
|
var from = calculator.Range(period).From;
|
||||||
|
|
||||||
|
// "Laufend" aus Sicht des Stichtags: alles nach dem letzten bis dahin beendeten Abschnitt.
|
||||||
|
var closed = sections.Where(s => s.EndDate <= asOf).ToList();
|
||||||
|
var openStart = timeline.OpenStart(closed, asOf);
|
||||||
|
if (openStart < from) openStart = from;
|
||||||
|
var running = openStart <= asOf ? timeline.ComputeSuggestion(studentId, openStart, asOf) : null;
|
||||||
|
|
||||||
|
var result = calculator.Calculate(studentId, period, rounding, asOf: asOf, runningParticipation: running);
|
||||||
|
return new InterimResult(period, result, running);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||||||
|
using CommunityToolkit.Mvvm.Input;
|
||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
// ── Zwischenstand starten (2.7.5) ────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// Legt einmal Stichtag, Anlass und Schülerauswahl fest; danach geht der Zeugnisnoten-Assistent
|
||||||
|
// im Zwischenstand-Modus nur die gewählten Schüler durch. Ganze Gruppe (Sprechtag, blaue
|
||||||
|
// Briefe), Teilgruppe (Konferenz) und Einzelfall (Elternanfrage, Abgang) sind derselbe Ablauf
|
||||||
|
// mit unterschiedlicher Auswahl.
|
||||||
|
public partial class InterimRunDialogViewModel : ObservableObject
|
||||||
|
{
|
||||||
|
private const string DateFormat = "dd.MM.yyyy";
|
||||||
|
private const string OtherOccasion = "Sonstiges";
|
||||||
|
|
||||||
|
private readonly IInterimGradeRepository _interimGrades;
|
||||||
|
private readonly InterimGradeCalculator _calculator;
|
||||||
|
private readonly ReportGradeCalculator _reportCalculator;
|
||||||
|
private readonly Dictionary<Guid, GroupMembership> _membershipsByStudent;
|
||||||
|
private readonly List<Student> _allStudents;
|
||||||
|
private readonly Guid _groupId;
|
||||||
|
private readonly GradingSystem _gradingSystem;
|
||||||
|
private readonly Guid? _preselectedStudentId;
|
||||||
|
|
||||||
|
public string GroupLabel { get; }
|
||||||
|
|
||||||
|
[ObservableProperty] private string _dateText;
|
||||||
|
[ObservableProperty] private string _dateTextError = "";
|
||||||
|
[ObservableProperty] private string _occasionName;
|
||||||
|
[ObservableProperty] private string _occasionDetail = "";
|
||||||
|
[ObservableProperty] private string _thresholdText;
|
||||||
|
[ObservableProperty] private string _thresholdTextError = "";
|
||||||
|
[ObservableProperty] private string _selectionError = "";
|
||||||
|
[ObservableProperty] private InterimRunChoice? _selectedExistingRun;
|
||||||
|
|
||||||
|
public string[] OccasionOptions { get; } =
|
||||||
|
["Sprechtag", "Blauer Brief", "Konferenz", "Elternanfrage", "Schülerrückfrage", "Abgang", OtherOccasion];
|
||||||
|
|
||||||
|
public ObservableCollection<InterimRunStudentRow> Students { get; } = [];
|
||||||
|
public List<InterimRunChoice> ExistingRuns { get; }
|
||||||
|
public bool HasExistingRuns => ExistingRuns.Count > 0;
|
||||||
|
public string AtRiskLabel => _gradingSystem == GradingSystem.Grades1To6
|
||||||
|
? "Nur gefährdete: Note ab" : "Nur gefährdete: Punkte bis";
|
||||||
|
|
||||||
|
/// Nach erfolgreichem <see cref="Confirm"/> gesetzt.
|
||||||
|
public InterimRunOptions? Result { get; private set; }
|
||||||
|
|
||||||
|
public InterimRunDialogViewModel(IGradeRepository grades, IExamRepository exams,
|
||||||
|
IExamResultRepository results, IStudentRepository students, IGroupMembershipRepository memberships,
|
||||||
|
IGradingSchemeRepository schemes, IReportGradeRepository reportGrades,
|
||||||
|
IParticipationSessionRepository participationSessions, IParticipationRepository participation,
|
||||||
|
IParticipationAspectRepository aspects, IParticipationSectionRepository sections,
|
||||||
|
IInterimGradeRepository interimGrades, GradingService grading,
|
||||||
|
Guid groupId, GroupType groupType, GradingSystem gradingSystem, string groupLabel, string schoolYear,
|
||||||
|
Guid? preselectedStudentId = null, DateOnly? today = null)
|
||||||
|
{
|
||||||
|
_interimGrades = interimGrades; _groupId = groupId; _gradingSystem = gradingSystem;
|
||||||
|
_preselectedStudentId = preselectedStudentId;
|
||||||
|
GroupLabel = groupLabel;
|
||||||
|
|
||||||
|
_membershipsByStudent = memberships.GetByGroup(groupId).ToDictionary(m => m.StudentId);
|
||||||
|
_allStudents = students.GetByGroup(groupId).OrderBy(s => s.LastName).ThenBy(s => s.FirstName).ToList();
|
||||||
|
var timeline = new ParticipationTimelineBuilder(participationSessions, participation, aspects, exams, results,
|
||||||
|
grades, _membershipsByStudent, grading, groupId, gradingSystem);
|
||||||
|
_reportCalculator = new ReportGradeCalculator(grades, exams, results, schemes, reportGrades,
|
||||||
|
_membershipsByStudent, grading, groupId, groupType, gradingSystem, schoolYear);
|
||||||
|
_calculator = new InterimGradeCalculator(_reportCalculator, timeline,
|
||||||
|
sections.GetByGroup(groupId).OrderBy(s => s.StartDate).ToList());
|
||||||
|
|
||||||
|
ExistingRuns = interimGrades.GetByGroup(groupId)
|
||||||
|
.GroupBy(g => (g.Date, g.Occasion))
|
||||||
|
.OrderByDescending(g => g.Key.Date)
|
||||||
|
.Select(g => new InterimRunChoice(g.Key.Date, g.Key.Occasion, g.Count()))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
_occasionName = OccasionOptions[0];
|
||||||
|
_thresholdText = gradingSystem == GradingSystem.Grades1To6 ? "5" : "4";
|
||||||
|
_dateText = (today ?? DateOnly.FromDateTime(DateTime.Today)).ToString(DateFormat);
|
||||||
|
RebuildStudents();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Occasion
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
var detail = OccasionDetail.Trim();
|
||||||
|
if (detail.Length == 0) return OccasionName;
|
||||||
|
return OccasionName == OtherOccasion ? detail : $"{OccasionName}: {detail}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnDateTextChanged(string value) => RebuildStudents();
|
||||||
|
partial void OnOccasionNameChanged(string value) => RefreshNotedMarkers();
|
||||||
|
partial void OnOccasionDetailChanged(string value) => RefreshNotedMarkers();
|
||||||
|
|
||||||
|
partial void OnSelectedExistingRunChanged(InterimRunChoice? value)
|
||||||
|
{
|
||||||
|
if (value is null) return;
|
||||||
|
// Anlass zurück in Auswahl + Ergänzung zerlegen, damit derselbe Durchgang fortgesetzt wird.
|
||||||
|
var option = OccasionOptions.FirstOrDefault(o => o != OtherOccasion
|
||||||
|
&& (value.Occasion == o || value.Occasion.StartsWith(o + ": ", StringComparison.Ordinal)));
|
||||||
|
OccasionName = option ?? OtherOccasion;
|
||||||
|
OccasionDetail = option is null ? value.Occasion
|
||||||
|
: value.Occasion.Length > option.Length ? value.Occasion[(option.Length + 2)..] : "";
|
||||||
|
DateText = value.Date.ToString(DateFormat);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryParseDate(out DateOnly date)
|
||||||
|
{
|
||||||
|
DateTextError = "";
|
||||||
|
if (!DateOnly.TryParseExact(DateText.Trim(), DateFormat, null, DateTimeStyles.None, out date))
|
||||||
|
{
|
||||||
|
DateTextError = "Format TT.MM.JJJJ.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
var (from, to) = _reportCalculator.Range(ParticipationPeriod.FullYear);
|
||||||
|
if (date < from || date > to)
|
||||||
|
{
|
||||||
|
DateTextError = "Stichtag liegt außerhalb des Schuljahrs.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RebuildStudents()
|
||||||
|
{
|
||||||
|
// Auswahl über den Neuaufbau retten; beim ersten Aufbau gilt die Vorauswahl.
|
||||||
|
var previous = Students.ToDictionary(s => s.StudentId, s => s.IsSelected);
|
||||||
|
Students.Clear();
|
||||||
|
if (!TryParseDate(out var date)) return;
|
||||||
|
|
||||||
|
foreach (var student in _allStudents)
|
||||||
|
{
|
||||||
|
if (_membershipsByStudent.TryGetValue(student.Id, out var membership)
|
||||||
|
&& !GroupMembershipService.IsActiveOn(membership, date)) continue;
|
||||||
|
var result = _calculator.Calculate(student.Id, date, RoundingRule.Commercial).Result;
|
||||||
|
var selected = previous.TryGetValue(student.Id, out var was)
|
||||||
|
? was
|
||||||
|
: _preselectedStudentId is null || _preselectedStudentId == student.Id;
|
||||||
|
Students.Add(new InterimRunStudentRow(student.Id, student.FullName, result.Rounded) { IsSelected = selected });
|
||||||
|
}
|
||||||
|
RefreshNotedMarkers();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshNotedMarkers()
|
||||||
|
{
|
||||||
|
if (!DateOnly.TryParseExact(DateText.Trim(), DateFormat, null, DateTimeStyles.None, out var date)) return;
|
||||||
|
var noted = _interimGrades.GetByGroup(_groupId)
|
||||||
|
.Where(g => g.Date == date && g.Occasion == Occasion)
|
||||||
|
.GroupBy(g => g.StudentId).ToDictionary(g => g.Key, g => g.First().OverallValue);
|
||||||
|
foreach (var row in Students)
|
||||||
|
row.NotedDisplay = noted.TryGetValue(row.StudentId, out var value) ? $"notiert: {value}" : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void SelectAll() { foreach (var row in Students) row.IsSelected = true; }
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void SelectNone() { foreach (var row in Students) row.IsSelected = false; }
|
||||||
|
|
||||||
|
/// Wählt genau die Schüler, deren vorläufige Note die Schwelle erreicht — für blaue Briefe.
|
||||||
|
[RelayCommand]
|
||||||
|
private void SelectAtRisk()
|
||||||
|
{
|
||||||
|
ThresholdTextError = "";
|
||||||
|
if (!int.TryParse(ThresholdText.Trim(), out var threshold))
|
||||||
|
{
|
||||||
|
ThresholdTextError = "Ganze Zahl erforderlich.";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach (var row in Students)
|
||||||
|
row.IsSelected = int.TryParse(row.ProvisionalGrade, out var grade)
|
||||||
|
&& (_gradingSystem == GradingSystem.Grades1To6 ? grade >= threshold : grade <= threshold);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Confirm()
|
||||||
|
{
|
||||||
|
SelectionError = "";
|
||||||
|
var valid = TryParseDate(out var date);
|
||||||
|
var selected = Students.Where(s => s.IsSelected).Select(s => s.StudentId).ToList();
|
||||||
|
if (valid && selected.Count == 0) { SelectionError = "Mindestens einen Schüler auswählen."; valid = false; }
|
||||||
|
if (!valid) return false;
|
||||||
|
|
||||||
|
Result = new InterimRunOptions(date, Occasion, selected);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class InterimRunChoice(DateOnly date, string occasion, int count)
|
||||||
|
{
|
||||||
|
public DateOnly Date { get; } = date;
|
||||||
|
public string Occasion { get; } = occasion;
|
||||||
|
public override string ToString() => $"{Date:dd.MM.yyyy} · {Occasion} ({count} notiert)";
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class InterimRunStudentRow(Guid studentId, string name, string? provisionalGrade) : ObservableObject
|
||||||
|
{
|
||||||
|
public Guid StudentId { get; } = studentId;
|
||||||
|
public string Name { get; } = name;
|
||||||
|
public string? ProvisionalGrade { get; } = provisionalGrade;
|
||||||
|
public string ProvisionalDisplay => ProvisionalGrade ?? "–";
|
||||||
|
|
||||||
|
[ObservableProperty] private bool _isSelected;
|
||||||
|
[ObservableProperty] private string _notedDisplay = "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
using CommunityToolkit.Mvvm.Input;
|
||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Baut die Zeitleisten-Punkte eines Schülers (Mitarbeit-Sitzungen, Arbeiten, sonstige Noten) für
|
||||||
|
/// <c>ParticipationTimelineChart</c>. Gemeinsame Grundlage von Mitarbeits-Assistent und
|
||||||
|
/// Zeugnisnoten-Assistent, damit beide denselben Graphen mit denselben Regeln zeigen.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ParticipationTimelineBuilder
|
||||||
|
{
|
||||||
|
/// Kennzeichnet in <see cref="Grade.Note"/> eine Abschnittsnote der Mitarbeit.
|
||||||
|
public const string SectionNotePrefix = "Abschnitt: ";
|
||||||
|
|
||||||
|
private readonly IParticipationRepository _entries;
|
||||||
|
private readonly IExamRepository _exams;
|
||||||
|
private readonly IExamResultRepository _results;
|
||||||
|
private readonly IGradeRepository _grades;
|
||||||
|
private readonly IReadOnlyDictionary<Guid, GroupMembership> _membershipsByStudent;
|
||||||
|
private readonly GradingService _grading;
|
||||||
|
private readonly Guid _groupId;
|
||||||
|
private readonly GradingSystem _gradingSystem;
|
||||||
|
private readonly List<ParticipationSession> _sessions;
|
||||||
|
private readonly Dictionary<string, double> _aspectWeights;
|
||||||
|
// Für die Normierung von Punkte-Aspekten (3.1.3) auf die gemeinsame -2..+2-Achse vor der
|
||||||
|
// Gewichtung, analog zu ParticipationGradeDialogViewModel.
|
||||||
|
private readonly Dictionary<string, ParticipationAspect> _aspectsByKey;
|
||||||
|
|
||||||
|
public IReadOnlyList<ParticipationSession> Sessions => _sessions;
|
||||||
|
|
||||||
|
public ParticipationTimelineBuilder(
|
||||||
|
IParticipationSessionRepository sessions, IParticipationRepository entries,
|
||||||
|
IParticipationAspectRepository aspects, IExamRepository exams, IExamResultRepository results,
|
||||||
|
IGradeRepository grades, IReadOnlyDictionary<Guid, GroupMembership> membershipsByStudent,
|
||||||
|
GradingService grading, Guid groupId, GradingSystem gradingSystem)
|
||||||
|
{
|
||||||
|
_entries = entries; _exams = exams; _results = results; _grades = grades;
|
||||||
|
_membershipsByStudent = membershipsByStudent; _grading = grading;
|
||||||
|
_groupId = groupId; _gradingSystem = gradingSystem;
|
||||||
|
|
||||||
|
var applicableAspects = aspects.GetDefaults().Concat(aspects.GetByGroup(groupId))
|
||||||
|
.GroupBy(a => a.Key).Select(g => g.Last()).ToList();
|
||||||
|
_aspectWeights = applicableAspects.ToDictionary(a => a.Key, a => a.Weight);
|
||||||
|
_aspectsByKey = applicableAspects.ToDictionary(a => a.Key);
|
||||||
|
_sessions = sessions.GetByGroup(groupId).OrderBy(s => s.Date).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string BandLabel(ParticipationSection section) =>
|
||||||
|
$"{section.Label}\n{section.StartDate:dd.MM.}–{section.EndDate:dd.MM.}";
|
||||||
|
|
||||||
|
public static string OpenBandLabel(DateOnly openStart) => $"läuft seit {openStart:dd.MM.}";
|
||||||
|
|
||||||
|
/// Beginn des laufenden, noch nicht abgeschlossenen Abschnitts.
|
||||||
|
public DateOnly OpenStart(IReadOnlyCollection<ParticipationSection> sections, DateOnly today) =>
|
||||||
|
sections.Count > 0 ? sections.Max(s => s.EndDate).AddDays(1)
|
||||||
|
: (_sessions.Count > 0 ? _sessions.Min(s => s.Date) : today);
|
||||||
|
|
||||||
|
public bool IsStudentActiveOn(Guid studentId, DateOnly date) =>
|
||||||
|
!_membershipsByStudent.TryGetValue(studentId, out var membership)
|
||||||
|
|| GroupMembershipService.IsActiveOn(membership, date);
|
||||||
|
|
||||||
|
/// Alle Punkte des Schülers, chronologisch sortiert.
|
||||||
|
public List<WizardTimelinePoint> BuildPoints(Guid studentId)
|
||||||
|
{
|
||||||
|
var points = new List<WizardTimelinePoint>();
|
||||||
|
|
||||||
|
foreach (var session in _sessions)
|
||||||
|
{
|
||||||
|
if (!IsStudentActiveOn(studentId, session.Date)) continue;
|
||||||
|
var entry = _entries.GetBySessionAndStudent(session.Id, studentId);
|
||||||
|
points.Add(BuildSessionPoint(session, entry, studentId));
|
||||||
|
}
|
||||||
|
foreach (var exam in _exams.GetByGroup(_groupId).OrderBy(e => e.Date))
|
||||||
|
{
|
||||||
|
if (!IsStudentActiveOn(studentId, exam.Date)) continue;
|
||||||
|
var result = _results.GetByExamAndStudent(exam.Id, studentId);
|
||||||
|
if (result is null) continue;
|
||||||
|
points.Add(BuildExamPoint(exam, result));
|
||||||
|
}
|
||||||
|
foreach (var grade in _grades.GetByStudentAndGroup(studentId, _groupId)
|
||||||
|
.Where(g => g.Category != GradeCategory.Participation)
|
||||||
|
.Where(g => IsStudentActiveOn(studentId, g.Date)))
|
||||||
|
{
|
||||||
|
points.Add(BuildOtherGradePoint(grade));
|
||||||
|
}
|
||||||
|
return points.OrderBy(p => p.Date).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Notenvorschlag aus den bewerteten Sitzungen im Zeitraum; null ohne bewertete Sitzung.
|
||||||
|
public string? ComputeSuggestion(Guid studentId, DateOnly start, DateOnly end)
|
||||||
|
{
|
||||||
|
var points = new List<double>();
|
||||||
|
foreach (var session in _sessions.Where(s => s.Date >= start && s.Date <= end)
|
||||||
|
.Where(s => IsStudentActiveOn(studentId, s.Date)))
|
||||||
|
{
|
||||||
|
var entry = _entries.GetBySessionAndStudent(session.Id, studentId);
|
||||||
|
if (entry is null) continue;
|
||||||
|
var weighted = WeightedRating(entry);
|
||||||
|
if (weighted is not null) points.Add(weighted.Value);
|
||||||
|
}
|
||||||
|
return points.Count == 0 ? null : _grading.ParticipationGrade(points.Average(), _gradingSystem);
|
||||||
|
}
|
||||||
|
|
||||||
|
private WizardTimelinePoint BuildSessionPoint(ParticipationSession session, ParticipationEntry? entry, Guid studentId)
|
||||||
|
{
|
||||||
|
var weightedValue = entry is not null ? WeightedRating(entry) : null;
|
||||||
|
var ratingLabel = weightedValue is not null ? RatingLabel((int)Math.Round(weightedValue.Value, MidpointRounding.AwayFromZero)) : "";
|
||||||
|
var note = entry?.Note;
|
||||||
|
var tooltip = $"{session.Date:dd.MM.yyyy}" +
|
||||||
|
(ratingLabel.Length > 0 ? $" · {ratingLabel}" : "") +
|
||||||
|
(string.IsNullOrWhiteSpace(note) ? "" : $" · {note}");
|
||||||
|
|
||||||
|
var point = new WizardTimelinePoint(session.Date, isExam: false, ratingLabel, examLabel: "",
|
||||||
|
hasNote: !string.IsNullOrWhiteSpace(note), tooltip: tooltip)
|
||||||
|
{
|
||||||
|
Homework = entry is null ? null : HomeworkDisplay.Effective(entry),
|
||||||
|
AttendanceIcon = AttendanceDisplay.ShortLabel(entry?.Attendance),
|
||||||
|
AttendanceTooltip = AttendanceDisplay.Label(entry?.Attendance),
|
||||||
|
AttendanceColor = AttendanceDisplay.Color(entry?.Attendance),
|
||||||
|
AspectValues = entry?.Ratings.ToDictionary(r => r.Key, r => r.Value)
|
||||||
|
?? new Dictionary<string, int>(),
|
||||||
|
WeightedValue = weightedValue,
|
||||||
|
OverallGrade = weightedValue is null ? "" : _grading.ParticipationGrade(weightedValue.Value, _gradingSystem),
|
||||||
|
};
|
||||||
|
point.ToggleHomeworkCommand = new RelayCommand(() => ToggleHomeworkAt(session.Id, studentId, point));
|
||||||
|
point.CycleAttendanceCommand = new RelayCommand(() => CycleAttendanceAt(session.Id, studentId, point));
|
||||||
|
return point;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WizardTimelinePoint BuildExamPoint(Exam exam, ExamResult result)
|
||||||
|
{
|
||||||
|
var examLabel = result.Absent ? $"{exam.Title}: abw." : $"{exam.Title}: {result.Grade}";
|
||||||
|
return new WizardTimelinePoint(exam.Date, isExam: true, ratingLabel: "", examLabel: examLabel,
|
||||||
|
hasNote: false, tooltip: $"{exam.Date:dd.MM.yyyy} · Klausur {examLabel}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WizardTimelinePoint BuildOtherGradePoint(Grade grade)
|
||||||
|
{
|
||||||
|
var category = grade.Category switch
|
||||||
|
{
|
||||||
|
GradeCategory.Oral => "Mündlich",
|
||||||
|
GradeCategory.Homework => "Hausaufgabe",
|
||||||
|
GradeCategory.Project => "Projekt",
|
||||||
|
_ => "Sonstige Leistung",
|
||||||
|
};
|
||||||
|
var detail = string.IsNullOrWhiteSpace(grade.Note) ? category : grade.Note.Trim();
|
||||||
|
var label = $"{detail}: {grade.Value}";
|
||||||
|
return new WizardTimelinePoint(grade.Date, isExam: true, ratingLabel: "", examLabel: label,
|
||||||
|
hasNote: false, tooltip: $"{grade.Date:dd.MM.yyyy} · {category} · {label}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private double? WeightedRating(ParticipationEntry entry)
|
||||||
|
{
|
||||||
|
if (entry.Ratings.Count == 0) return null;
|
||||||
|
var weightSum = 0.0; var valueSum = 0.0;
|
||||||
|
foreach (var r in entry.Ratings)
|
||||||
|
{
|
||||||
|
var w = _aspectWeights.TryGetValue(r.Key, out var aw) ? aw : 1.0;
|
||||||
|
if (w <= 0) continue;
|
||||||
|
valueSum += NormalizedValue(r) * w; weightSum += w;
|
||||||
|
}
|
||||||
|
return weightSum <= 0 ? null : valueSum / weightSum;
|
||||||
|
}
|
||||||
|
|
||||||
|
private double NormalizedValue(AspectRating r) => _aspectsByKey.TryGetValue(r.Key, out var aspect)
|
||||||
|
? ParticipationRatingScale.Normalize(aspect.ValueType, r.Value, aspect.MaxPoints)
|
||||||
|
: r.Value;
|
||||||
|
|
||||||
|
private static string RatingLabel(int v) => v switch
|
||||||
|
{
|
||||||
|
>= 2 => "++", 1 => "+", 0 => "~", -1 => "−", _ => "−−",
|
||||||
|
};
|
||||||
|
|
||||||
|
private void ToggleHomeworkAt(Guid sessionId, Guid studentId, WizardTimelinePoint point)
|
||||||
|
{
|
||||||
|
var entry = _entries.GetBySessionAndStudent(sessionId, studentId)
|
||||||
|
?? new ParticipationEntry { SessionId = sessionId, StudentId = studentId };
|
||||||
|
entry.Homework = HomeworkDisplay.Next(HomeworkDisplay.Effective(entry));
|
||||||
|
entry.HomeworkMissing = HomeworkDisplay.CountsAsMissing(entry.Homework);
|
||||||
|
_entries.Save(entry);
|
||||||
|
point.Homework = entry.Homework;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CycleAttendanceAt(Guid sessionId, Guid studentId, WizardTimelinePoint point)
|
||||||
|
{
|
||||||
|
var entry = _entries.GetBySessionAndStudent(sessionId, studentId)
|
||||||
|
?? new ParticipationEntry { SessionId = sessionId, StudentId = studentId };
|
||||||
|
entry.Attendance = entry.Attendance switch
|
||||||
|
{
|
||||||
|
null => AttendanceStatus.Present,
|
||||||
|
AttendanceStatus.Present => AttendanceStatus.ExcusePending,
|
||||||
|
AttendanceStatus.ExcusePending => AttendanceStatus.Excused,
|
||||||
|
AttendanceStatus.Excused => AttendanceStatus.Unexcused,
|
||||||
|
AttendanceStatus.Unexcused => AttendanceStatus.Truant,
|
||||||
|
AttendanceStatus.Truant => AttendanceStatus.OtherSchoolEvent,
|
||||||
|
AttendanceStatus.OtherSchoolEvent => null,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
_entries.Save(entry);
|
||||||
|
// Das Setzen jeder ObservableProperty kann unmittelbar ein Neuzeichnen auslösen.
|
||||||
|
// Deshalb muss die zum aktiven Symbol gehörende Farbe zuerst bereitstehen.
|
||||||
|
point.AttendanceColor = AttendanceDisplay.Color(entry.Attendance);
|
||||||
|
point.AttendanceTooltip = AttendanceDisplay.Label(entry.Attendance);
|
||||||
|
point.AttendanceIcon = AttendanceDisplay.ShortLabel(entry.Attendance);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,13 +12,9 @@ namespace LehrerApp.Desktop.ViewModels.Groups;
|
|||||||
|
|
||||||
public partial class ParticipationWizardDialogViewModel : ObservableObject
|
public partial class ParticipationWizardDialogViewModel : ObservableObject
|
||||||
{
|
{
|
||||||
private const string AbschnittPrefix = "Abschnitt: ";
|
private const string AbschnittPrefix = ParticipationTimelineBuilder.SectionNotePrefix;
|
||||||
|
|
||||||
private readonly IParticipationSessionRepository _sessions;
|
|
||||||
private readonly IParticipationRepository _entries;
|
|
||||||
private readonly IParticipationSectionRepository _sectionRepo;
|
private readonly IParticipationSectionRepository _sectionRepo;
|
||||||
private readonly IExamRepository _exams;
|
|
||||||
private readonly IExamResultRepository _results;
|
|
||||||
private readonly IGradeRepository _grades;
|
private readonly IGradeRepository _grades;
|
||||||
private readonly IUnitRepository _units;
|
private readonly IUnitRepository _units;
|
||||||
private readonly Dictionary<Guid, GroupMembership> _membershipsByStudent;
|
private readonly Dictionary<Guid, GroupMembership> _membershipsByStudent;
|
||||||
@@ -28,12 +24,8 @@ public partial class ParticipationWizardDialogViewModel : ObservableObject
|
|||||||
private readonly GradingSystem _gradingSystem;
|
private readonly GradingSystem _gradingSystem;
|
||||||
|
|
||||||
private readonly List<Student> _students;
|
private readonly List<Student> _students;
|
||||||
private readonly List<ParticipationSession> _allSessions;
|
|
||||||
private readonly List<ParticipationSection> _sectionList;
|
private readonly List<ParticipationSection> _sectionList;
|
||||||
private readonly Dictionary<string, double> _aspectWeights;
|
private readonly ParticipationTimelineBuilder _timeline;
|
||||||
// Für die Normierung von Punkte-Aspekten (3.1.3) auf die gemeinsame -2..+2-Achse vor der
|
|
||||||
// Gewichtung, analog zu ParticipationGradeDialogViewModel.
|
|
||||||
private readonly Dictionary<string, ParticipationAspect> _aspectsByKey;
|
|
||||||
|
|
||||||
public string GroupLabel { get; }
|
public string GroupLabel { get; }
|
||||||
|
|
||||||
@@ -79,22 +71,19 @@ public partial class ParticipationWizardDialogViewModel : ObservableObject
|
|||||||
IGradeRepository grades, IUnitRepository units, GradingService grading,
|
IGradeRepository grades, IUnitRepository units, GradingService grading,
|
||||||
Guid groupId, string schoolYear, GradingSystem gradingSystem, string groupLabel)
|
Guid groupId, string schoolYear, GradingSystem gradingSystem, string groupLabel)
|
||||||
{
|
{
|
||||||
_sessions = sessions; _entries = entries; _sectionRepo = sectionRepo;
|
_sectionRepo = sectionRepo;
|
||||||
_exams = exams; _results = results; _grades = grades; _units = units; _grading = grading;
|
_grades = grades; _units = units; _grading = grading;
|
||||||
_groupId = groupId; _schoolYear = schoolYear; _gradingSystem = gradingSystem;
|
_groupId = groupId; _schoolYear = schoolYear; _gradingSystem = gradingSystem;
|
||||||
GroupLabel = groupLabel;
|
GroupLabel = groupLabel;
|
||||||
_membershipsByStudent = memberships.GetByGroup(groupId).ToDictionary(m => m.StudentId);
|
_membershipsByStudent = memberships.GetByGroup(groupId).ToDictionary(m => m.StudentId);
|
||||||
|
|
||||||
var applicableAspects = aspects.GetDefaults().Concat(aspects.GetByGroup(groupId))
|
_timeline = new ParticipationTimelineBuilder(sessions, entries, aspects, exams, results, grades,
|
||||||
.GroupBy(a => a.Key).Select(g => g.Last()).ToList();
|
_membershipsByStudent, grading, groupId, gradingSystem);
|
||||||
_aspectWeights = applicableAspects.ToDictionary(a => a.Key, a => a.Weight);
|
|
||||||
_aspectsByKey = applicableAspects.ToDictionary(a => a.Key);
|
|
||||||
var schoolYearRange = GroupMembershipService.SchoolYearPeriod(schoolYear, SchoolYearPeriodKind.FullYear);
|
var schoolYearRange = GroupMembershipService.SchoolYearPeriod(schoolYear, SchoolYearPeriodKind.FullYear);
|
||||||
_students = students.GetByGroup(groupId)
|
_students = students.GetByGroup(groupId)
|
||||||
.Where(s => !_membershipsByStudent.TryGetValue(s.Id, out var membership)
|
.Where(s => !_membershipsByStudent.TryGetValue(s.Id, out var membership)
|
||||||
|| GroupMembershipService.Overlaps(membership, schoolYearRange.From, schoolYearRange.To))
|
|| GroupMembershipService.Overlaps(membership, schoolYearRange.From, schoolYearRange.To))
|
||||||
.OrderBy(s => s.LastName).ThenBy(s => s.FirstName).ToList();
|
.OrderBy(s => s.LastName).ThenBy(s => s.FirstName).ToList();
|
||||||
_allSessions = sessions.GetByGroup(groupId).OrderBy(s => s.Date).ToList();
|
|
||||||
_sectionList = sectionRepo.GetByGroup(groupId).OrderBy(s => s.StartDate).ToList();
|
_sectionList = sectionRepo.GetByGroup(groupId).OrderBy(s => s.StartDate).ToList();
|
||||||
|
|
||||||
_rollupPeriod = RollupPeriodOptions[0];
|
_rollupPeriod = RollupPeriodOptions[0];
|
||||||
@@ -131,153 +120,28 @@ public partial class ParticipationWizardDialogViewModel : ObservableObject
|
|||||||
|
|
||||||
private void BuildTimeline(Guid studentId)
|
private void BuildTimeline(Guid studentId)
|
||||||
{
|
{
|
||||||
var points = new List<(DateOnly Date, WizardTimelinePoint Point)>();
|
var points = _timeline.BuildPoints(studentId);
|
||||||
|
|
||||||
foreach (var session in _allSessions)
|
|
||||||
{
|
|
||||||
if (!IsStudentActiveOn(studentId, session.Date)) continue;
|
|
||||||
var entry = _entries.GetBySessionAndStudent(session.Id, studentId);
|
|
||||||
points.Add((session.Date, BuildSessionPoint(session, entry, studentId)));
|
|
||||||
}
|
|
||||||
foreach (var exam in _exams.GetByGroup(_groupId).OrderBy(e => e.Date))
|
|
||||||
{
|
|
||||||
if (!IsStudentActiveOn(studentId, exam.Date)) continue;
|
|
||||||
var result = _results.GetByExamAndStudent(exam.Id, studentId);
|
|
||||||
if (result is null) continue;
|
|
||||||
points.Add((exam.Date, BuildExamPoint(exam, result)));
|
|
||||||
}
|
|
||||||
foreach (var grade in _grades.GetByStudentAndGroup(studentId, _groupId)
|
|
||||||
.Where(g => g.Category != GradeCategory.Participation)
|
|
||||||
.Where(g => IsStudentActiveOn(studentId, g.Date)))
|
|
||||||
{
|
|
||||||
points.Add((grade.Date, BuildOtherGradePoint(grade)));
|
|
||||||
}
|
|
||||||
points = points.OrderBy(p => p.Date).ToList();
|
|
||||||
|
|
||||||
Timeline.Clear();
|
Timeline.Clear();
|
||||||
foreach (var section in _sectionList)
|
foreach (var section in _sectionList)
|
||||||
{
|
{
|
||||||
var group = new WizardSectionGroup($"{section.Label}\n{section.StartDate:dd.MM.}–{section.EndDate:dd.MM.}", isOpen: false);
|
var group = new WizardSectionGroup(ParticipationTimelineBuilder.BandLabel(section), isOpen: false);
|
||||||
foreach (var (date, point) in points.Where(p => p.Date >= section.StartDate && p.Date <= section.EndDate))
|
foreach (var point in points.Where(p => p.Date >= section.StartDate && p.Date <= section.EndDate))
|
||||||
group.Points.Add(point);
|
group.Points.Add(point);
|
||||||
Timeline.Add(group);
|
Timeline.Add(group);
|
||||||
}
|
}
|
||||||
|
|
||||||
var openStart = ComputeOpenStart();
|
var openStart = ComputeOpenStart();
|
||||||
var openGroup = new WizardSectionGroup($"läuft seit {openStart:dd.MM.}", isOpen: true);
|
var openGroup = new WizardSectionGroup(ParticipationTimelineBuilder.OpenBandLabel(openStart), isOpen: true);
|
||||||
foreach (var (date, point) in points.Where(p => p.Date >= openStart))
|
foreach (var point in points.Where(p => p.Date >= openStart))
|
||||||
openGroup.Points.Add(point);
|
openGroup.Points.Add(point);
|
||||||
Timeline.Add(openGroup);
|
Timeline.Add(openGroup);
|
||||||
}
|
}
|
||||||
|
|
||||||
private WizardTimelinePoint BuildSessionPoint(ParticipationSession session, ParticipationEntry? entry, Guid studentId)
|
|
||||||
{
|
|
||||||
var weightedValue = entry is not null ? WeightedRating(entry) : null;
|
|
||||||
var ratingLabel = weightedValue is not null ? RatingLabel((int)Math.Round(weightedValue.Value, MidpointRounding.AwayFromZero)) : "";
|
|
||||||
var note = entry?.Note;
|
|
||||||
var tooltip = $"{session.Date:dd.MM.yyyy}" +
|
|
||||||
(ratingLabel.Length > 0 ? $" · {ratingLabel}" : "") +
|
|
||||||
(string.IsNullOrWhiteSpace(note) ? "" : $" · {note}");
|
|
||||||
|
|
||||||
var point = new WizardTimelinePoint(session.Date, isExam: false, ratingLabel, examLabel: "",
|
|
||||||
hasNote: !string.IsNullOrWhiteSpace(note), tooltip: tooltip)
|
|
||||||
{
|
|
||||||
Homework = entry is null ? null : HomeworkDisplay.Effective(entry),
|
|
||||||
AttendanceIcon = AttendanceDisplay.ShortLabel(entry?.Attendance),
|
|
||||||
AttendanceTooltip = AttendanceDisplay.Label(entry?.Attendance),
|
|
||||||
AttendanceColor = AttendanceDisplay.Color(entry?.Attendance),
|
|
||||||
AspectValues = entry?.Ratings.ToDictionary(r => r.Key, r => r.Value)
|
|
||||||
?? new Dictionary<string, int>(),
|
|
||||||
WeightedValue = weightedValue,
|
|
||||||
OverallGrade = weightedValue is null ? "" : _grading.ParticipationGrade(weightedValue.Value, _gradingSystem),
|
|
||||||
};
|
|
||||||
point.ToggleHomeworkCommand = new RelayCommand(() => ToggleHomeworkAt(session.Id, studentId, point));
|
|
||||||
point.CycleAttendanceCommand = new RelayCommand(() => CycleAttendanceAt(session.Id, studentId, point));
|
|
||||||
return point;
|
|
||||||
}
|
|
||||||
|
|
||||||
private WizardTimelinePoint BuildExamPoint(Exam exam, ExamResult result)
|
|
||||||
{
|
|
||||||
var examLabel = result.Absent ? $"{exam.Title}: abw." : $"{exam.Title}: {result.Grade}";
|
|
||||||
return new WizardTimelinePoint(exam.Date, isExam: true, ratingLabel: "", examLabel: examLabel,
|
|
||||||
hasNote: false, tooltip: $"{exam.Date:dd.MM.yyyy} · Klausur {examLabel}");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static WizardTimelinePoint BuildOtherGradePoint(Grade grade)
|
|
||||||
{
|
|
||||||
var category = grade.Category switch
|
|
||||||
{
|
|
||||||
GradeCategory.Oral => "Mündlich",
|
|
||||||
GradeCategory.Homework => "Hausaufgabe",
|
|
||||||
GradeCategory.Project => "Projekt",
|
|
||||||
_ => "Sonstige Leistung",
|
|
||||||
};
|
|
||||||
var detail = string.IsNullOrWhiteSpace(grade.Note) ? category : grade.Note.Trim();
|
|
||||||
var label = $"{detail}: {grade.Value}";
|
|
||||||
return new WizardTimelinePoint(grade.Date, isExam: true, ratingLabel: "", examLabel: label,
|
|
||||||
hasNote: false, tooltip: $"{grade.Date:dd.MM.yyyy} · {category} · {label}");
|
|
||||||
}
|
|
||||||
|
|
||||||
private double? WeightedRating(ParticipationEntry entry)
|
|
||||||
{
|
|
||||||
if (entry.Ratings.Count == 0) return null;
|
|
||||||
var weightSum = 0.0; var valueSum = 0.0;
|
|
||||||
foreach (var r in entry.Ratings)
|
|
||||||
{
|
|
||||||
var w = _aspectWeights.TryGetValue(r.Key, out var aw) ? aw : 1.0;
|
|
||||||
if (w <= 0) continue;
|
|
||||||
valueSum += NormalizedValue(r) * w; weightSum += w;
|
|
||||||
}
|
|
||||||
return weightSum <= 0 ? null : valueSum / weightSum;
|
|
||||||
}
|
|
||||||
|
|
||||||
private double NormalizedValue(AspectRating r) => _aspectsByKey.TryGetValue(r.Key, out var aspect)
|
|
||||||
? ParticipationRatingScale.Normalize(aspect.ValueType, r.Value, aspect.MaxPoints)
|
|
||||||
: r.Value;
|
|
||||||
|
|
||||||
private static string RatingLabel(int v) => v switch
|
|
||||||
{
|
|
||||||
>= 2 => "++", 1 => "+", 0 => "~", -1 => "−", _ => "−−",
|
|
||||||
};
|
|
||||||
|
|
||||||
private void ToggleHomeworkAt(Guid sessionId, Guid studentId, WizardTimelinePoint point)
|
|
||||||
{
|
|
||||||
var entry = _entries.GetBySessionAndStudent(sessionId, studentId)
|
|
||||||
?? new ParticipationEntry { SessionId = sessionId, StudentId = studentId };
|
|
||||||
entry.Homework = HomeworkDisplay.Next(HomeworkDisplay.Effective(entry));
|
|
||||||
entry.HomeworkMissing = HomeworkDisplay.CountsAsMissing(entry.Homework);
|
|
||||||
_entries.Save(entry);
|
|
||||||
point.Homework = entry.Homework;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void CycleAttendanceAt(Guid sessionId, Guid studentId, WizardTimelinePoint point)
|
|
||||||
{
|
|
||||||
var entry = _entries.GetBySessionAndStudent(sessionId, studentId)
|
|
||||||
?? new ParticipationEntry { SessionId = sessionId, StudentId = studentId };
|
|
||||||
entry.Attendance = entry.Attendance switch
|
|
||||||
{
|
|
||||||
null => AttendanceStatus.Present,
|
|
||||||
AttendanceStatus.Present => AttendanceStatus.ExcusePending,
|
|
||||||
AttendanceStatus.ExcusePending => AttendanceStatus.Excused,
|
|
||||||
AttendanceStatus.Excused => AttendanceStatus.Unexcused,
|
|
||||||
AttendanceStatus.Unexcused => AttendanceStatus.Truant,
|
|
||||||
AttendanceStatus.Truant => AttendanceStatus.OtherSchoolEvent,
|
|
||||||
AttendanceStatus.OtherSchoolEvent => null,
|
|
||||||
_ => null,
|
|
||||||
};
|
|
||||||
_entries.Save(entry);
|
|
||||||
// Das Setzen jeder ObservableProperty kann unmittelbar ein Neuzeichnen auslösen.
|
|
||||||
// Deshalb muss die zum aktiven Symbol gehörende Farbe zuerst bereitstehen.
|
|
||||||
point.AttendanceColor = AttendanceDisplay.Color(entry.Attendance);
|
|
||||||
point.AttendanceTooltip = AttendanceDisplay.Label(entry.Attendance);
|
|
||||||
point.AttendanceIcon = AttendanceDisplay.ShortLabel(entry.Attendance);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Abschnitte ────────────────────────────────────────────────────────────
|
// ── Abschnitte ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
private DateOnly ComputeOpenStart() =>
|
private DateOnly ComputeOpenStart() =>
|
||||||
_sectionList.Count > 0 ? _sectionList.Max(s => s.EndDate).AddDays(1)
|
_timeline.OpenStart(_sectionList, DateOnly.FromDateTime(DateTime.Today));
|
||||||
: (_allSessions.Count > 0 ? _allSessions.Min(s => s.Date) : DateOnly.FromDateTime(DateTime.Today));
|
|
||||||
|
|
||||||
/// Schlägt als Abschnittsende bewusst nicht immer "heute" vor: Wenn seit Abschnittsbeginn
|
/// Schlägt als Abschnittsende bewusst nicht immer "heute" vor: Wenn seit Abschnittsbeginn
|
||||||
/// eine Unterrichtseinheit (4.2) abgeschlossen wurde, ist deren Ende meist die fachlich
|
/// eine Unterrichtseinheit (4.2) abgeschlossen wurde, ist deren Ende meist die fachlich
|
||||||
@@ -314,31 +178,11 @@ public partial class ParticipationWizardDialogViewModel : ObservableObject
|
|||||||
}
|
}
|
||||||
|
|
||||||
var openStart = ComputeOpenStart();
|
var openStart = ComputeOpenStart();
|
||||||
var suggestion = ComputeSuggestion(studentId, openStart, DateOnly.FromDateTime(DateTime.Today));
|
var suggestion = _timeline.ComputeSuggestion(studentId, openStart, DateOnly.FromDateTime(DateTime.Today));
|
||||||
Sections.Add(new WizardSectionRow("(läuft)", openStart, DateOnly.FromDateTime(DateTime.Today),
|
Sections.Add(new WizardSectionRow("(läuft)", openStart, DateOnly.FromDateTime(DateTime.Today),
|
||||||
suggestion ?? "", isOpen: true));
|
suggestion ?? "", isOpen: true));
|
||||||
}
|
}
|
||||||
|
|
||||||
private string? ComputeSuggestion(Guid studentId, DateOnly start, DateOnly end)
|
|
||||||
{
|
|
||||||
var points = new List<double>();
|
|
||||||
foreach (var session in _allSessions.Where(s => s.Date >= start && s.Date <= end)
|
|
||||||
.Where(s => IsStudentActiveOn(studentId, s.Date)))
|
|
||||||
{
|
|
||||||
var entry = _entries.GetBySessionAndStudent(session.Id, studentId);
|
|
||||||
if (entry is null || entry.Ratings.Count == 0) continue;
|
|
||||||
var weightSum = 0.0; var valueSum = 0.0;
|
|
||||||
foreach (var r in entry.Ratings)
|
|
||||||
{
|
|
||||||
var w = _aspectWeights.TryGetValue(r.Key, out var aw) ? aw : 1.0;
|
|
||||||
if (w <= 0) continue;
|
|
||||||
valueSum += NormalizedValue(r) * w; weightSum += w;
|
|
||||||
}
|
|
||||||
if (weightSum > 0) points.Add(valueSum / weightSum);
|
|
||||||
}
|
|
||||||
return points.Count == 0 ? null : _grading.ParticipationGrade(points.Average(), _gradingSystem);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void SaveSectionGrade(WizardSectionRow row)
|
private void SaveSectionGrade(WizardSectionRow row)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(row.Value)) { row.StatusMessage = "Wert darf nicht leer sein."; return; }
|
if (string.IsNullOrWhiteSpace(row.Value)) { row.StatusMessage = "Wert darf nicht leer sein."; return; }
|
||||||
@@ -382,7 +226,7 @@ public partial class ParticipationWizardDialogViewModel : ObservableObject
|
|||||||
|
|
||||||
foreach (var student in _students)
|
foreach (var student in _students)
|
||||||
{
|
{
|
||||||
var suggestion = ComputeSuggestion(student.Id, start, end);
|
var suggestion = _timeline.ComputeSuggestion(student.Id, start, end);
|
||||||
if (suggestion is null) continue;
|
if (suggestion is null) continue;
|
||||||
_grades.Save(new Grade
|
_grades.Save(new Grade
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ public partial class PersonalizeWorksheetDialogViewModel : ObservableObject
|
|||||||
IStudentRepository students, WorksheetTemplateStore templates, ITemplateRenderer renderer)
|
IStudentRepository students, WorksheetTemplateStore templates, ITemplateRenderer renderer)
|
||||||
{
|
{
|
||||||
_group = group; _templates = templates; _renderer = renderer;
|
_group = group; _templates = templates; _renderer = renderer;
|
||||||
foreach (var template in templates.Store.GetTemplates()) Templates.Add(new(template));
|
foreach (var template in templates.Store.GetTemplates().Where(x => !x.IsExamCover && !x.IsStudentReport)) Templates.Add(new(template));
|
||||||
SelectedTemplate = Templates.FirstOrDefault();
|
SelectedTemplate = Templates.FirstOrDefault();
|
||||||
foreach (var id in studentIds)
|
foreach (var id in studentIds)
|
||||||
if (students.GetById(id) is { } student) Students.Add(new(student));
|
if (students.GetById(id) is { } student) Students.Add(new(student));
|
||||||
|
|||||||
@@ -789,6 +789,10 @@ public partial class LessonDialogViewModel : ObservableObject
|
|||||||
// Für die KI-Unterstützung mit Fokus auf genau diese Stunde (4.5.22) — nur für bereits
|
// Für die KI-Unterstützung mit Fokus auf genau diese Stunde (4.5.22) — nur für bereits
|
||||||
// gespeicherte Stunden sinnvoll, eine gerade erst angelegte, noch ungespeicherte Stunde hat
|
// gespeicherte Stunden sinnvoll, eine gerade erst angelegte, noch ungespeicherte Stunde hat
|
||||||
// keine echte Id, auf die sich die KI beziehen könnte.
|
// keine echte Id, auf die sich die KI beziehen könnte.
|
||||||
|
// Persist a pending parent only after validation and before writing its first lesson.
|
||||||
|
public Action? BeforeSave { get; set; }
|
||||||
|
public void EnsureParentSaved() => BeforeSave?.Invoke();
|
||||||
|
|
||||||
public Guid UnitId => _unitId;
|
public Guid UnitId => _unitId;
|
||||||
public Guid GroupId => _groupId;
|
public Guid GroupId => _groupId;
|
||||||
public Lesson? EditingLesson => _editingLesson;
|
public Lesson? EditingLesson => _editingLesson;
|
||||||
@@ -1079,6 +1083,7 @@ public partial class LessonDialogViewModel : ObservableObject
|
|||||||
|
|
||||||
if (!valid) return;
|
if (!valid) return;
|
||||||
|
|
||||||
|
EnsureParentSaved();
|
||||||
Result = _editingLesson ?? new Lesson { UnitId = _unitId, GroupId = _groupId };
|
Result = _editingLesson ?? new Lesson { UnitId = _unitId, GroupId = _groupId };
|
||||||
Result.UnitId = _unitId;
|
Result.UnitId = _unitId;
|
||||||
Result.GroupId = _groupId;
|
Result.GroupId = _groupId;
|
||||||
|
|||||||
@@ -0,0 +1,200 @@
|
|||||||
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||||||
|
using CommunityToolkit.Mvvm.Input;
|
||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
public enum StudentDrawMode { FullRound, Intelligent }
|
||||||
|
|
||||||
|
public sealed record StudentDrawGroup(Guid Id, string Name);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Steuert das eigenstaendige Ziehfenster. Die Ziehhistorie ist bewusst nur fuer die Laufzeit
|
||||||
|
/// des Fensters gueltig; es entstehen dadurch keine zusaetzlichen personenbezogenen Datensaetze.
|
||||||
|
/// </summary>
|
||||||
|
public partial class RandomStudentPickerViewModel : ObservableObject
|
||||||
|
{
|
||||||
|
public const string FullRoundLabel = "Alle einmal, dann neu";
|
||||||
|
public const string IntelligentLabel = "Intelligent ausgleichen";
|
||||||
|
|
||||||
|
private readonly IStudentRepository _students;
|
||||||
|
private readonly IGroupMembershipRepository _memberships;
|
||||||
|
private readonly IParticipationSessionRepository _sessions;
|
||||||
|
private readonly IParticipationRepository _participation;
|
||||||
|
private readonly Random _random;
|
||||||
|
private readonly List<Student> _candidates = [];
|
||||||
|
private readonly List<Guid> _roundBag = [];
|
||||||
|
private readonly Dictionary<Guid, int> _drawCounts = [];
|
||||||
|
private readonly Dictionary<Guid, ParticipationSignal> _signals = [];
|
||||||
|
private Guid? _lastStudentId;
|
||||||
|
|
||||||
|
[ObservableProperty] private StudentDrawGroup? _selectedGroup;
|
||||||
|
[ObservableProperty] private string _selectionModeName = FullRoundLabel;
|
||||||
|
[ObservableProperty] private bool _considerParticipation = true;
|
||||||
|
[ObservableProperty] private string _selectedStudentName = "Bereit?";
|
||||||
|
[ObservableProperty] private string _statusText = "Wähle in den Optionen eine Lerngruppe.";
|
||||||
|
[ObservableProperty] private bool _hasDrawnStudent;
|
||||||
|
|
||||||
|
public ObservableCollection<StudentDrawGroup> Groups { get; } = [];
|
||||||
|
public string[] SelectionModeOptions { get; } = [FullRoundLabel, IntelligentLabel];
|
||||||
|
public bool IsIntelligent => SelectionModeName == IntelligentLabel;
|
||||||
|
public bool CanDraw => SelectedGroup is not null && _candidates.Count > 0;
|
||||||
|
|
||||||
|
public RandomStudentPickerViewModel(
|
||||||
|
IStudentRepository students,
|
||||||
|
IGroupRepository groups,
|
||||||
|
IGroupMembershipRepository memberships,
|
||||||
|
IParticipationSessionRepository sessions,
|
||||||
|
IParticipationRepository participation,
|
||||||
|
Guid? initialGroupId = null,
|
||||||
|
Random? random = null)
|
||||||
|
{
|
||||||
|
_students = students;
|
||||||
|
_memberships = memberships;
|
||||||
|
_sessions = sessions;
|
||||||
|
_participation = participation;
|
||||||
|
_random = random ?? Random.Shared;
|
||||||
|
|
||||||
|
foreach (var group in groups.GetAll().OrderBy(g => g.Name, StringComparer.CurrentCultureIgnoreCase))
|
||||||
|
Groups.Add(new StudentDrawGroup(group.Id, group.Name));
|
||||||
|
|
||||||
|
SelectedGroup = Groups.FirstOrDefault(g => g.Id == initialGroupId) ?? Groups.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnSelectedGroupChanged(StudentDrawGroup? value) => ReloadGroup();
|
||||||
|
|
||||||
|
partial void OnSelectionModeNameChanged(string value)
|
||||||
|
{
|
||||||
|
OnPropertyChanged(nameof(IsIntelligent));
|
||||||
|
ResetDrawState();
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnConsiderParticipationChanged(bool value) => ResetDrawState();
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanDraw))]
|
||||||
|
private void Draw()
|
||||||
|
{
|
||||||
|
var student = IsIntelligent ? DrawIntelligently() : DrawFromFullRound();
|
||||||
|
_drawCounts[student.Id] = _drawCounts.GetValueOrDefault(student.Id) + 1;
|
||||||
|
_lastStudentId = student.Id;
|
||||||
|
SelectedStudentName = student.FullName;
|
||||||
|
HasDrawnStudent = true;
|
||||||
|
UpdateStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void Reset() => ResetDrawState();
|
||||||
|
|
||||||
|
private void ReloadGroup()
|
||||||
|
{
|
||||||
|
_candidates.Clear();
|
||||||
|
_signals.Clear();
|
||||||
|
|
||||||
|
if (SelectedGroup is not null)
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var activeIds = _memberships.GetByGroup(SelectedGroup.Id)
|
||||||
|
.Where(m => GroupMembershipService.IsActiveOn(m, today))
|
||||||
|
.Select(m => m.StudentId)
|
||||||
|
.ToHashSet();
|
||||||
|
_candidates.AddRange(_students.GetByGroup(SelectedGroup.Id)
|
||||||
|
.Where(s => s.IsActive && activeIds.Contains(s.Id))
|
||||||
|
.OrderBy(s => s.LastName, StringComparer.CurrentCultureIgnoreCase)
|
||||||
|
.ThenBy(s => s.FirstName, StringComparer.CurrentCultureIgnoreCase));
|
||||||
|
LoadParticipationSignals(SelectedGroup.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
ResetDrawState();
|
||||||
|
OnPropertyChanged(nameof(CanDraw));
|
||||||
|
DrawCommand.NotifyCanExecuteChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadParticipationSignals(Guid groupId)
|
||||||
|
{
|
||||||
|
var sessionIds = _sessions.GetByGroup(groupId).Select(s => s.Id).ToList();
|
||||||
|
var entries = sessionIds.SelectMany(_participation.GetBySession).ToList();
|
||||||
|
|
||||||
|
foreach (var student in _candidates)
|
||||||
|
{
|
||||||
|
var own = entries.Where(e => e.StudentId == student.Id).ToList();
|
||||||
|
var activity = own.Sum(e => e.RaisedHandCount + e.CalledOnCount);
|
||||||
|
var values = own.SelectMany(e => e.Ratings).Select(r => Math.Clamp(r.Value, -2, 2)).ToList();
|
||||||
|
_signals[student.Id] = new ParticipationSignal(
|
||||||
|
activity,
|
||||||
|
values.Count == 0 ? null : values.Average());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Student DrawFromFullRound()
|
||||||
|
{
|
||||||
|
if (_roundBag.Count == 0)
|
||||||
|
{
|
||||||
|
_roundBag.AddRange(_candidates.Select(s => s.Id));
|
||||||
|
for (var i = _roundBag.Count - 1; i > 0; i--)
|
||||||
|
{
|
||||||
|
var swap = _random.Next(i + 1);
|
||||||
|
(_roundBag[i], _roundBag[swap]) = (_roundBag[swap], _roundBag[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var id = _roundBag[^1];
|
||||||
|
_roundBag.RemoveAt(_roundBag.Count - 1);
|
||||||
|
return _candidates.Single(s => s.Id == id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Student DrawIntelligently()
|
||||||
|
{
|
||||||
|
var maxActivity = Math.Max(1, _signals.Values.Select(s => s.Activity).DefaultIfEmpty().Max());
|
||||||
|
var eligible = _candidates.Count > 1
|
||||||
|
? _candidates.Where(student => student.Id != _lastStudentId)
|
||||||
|
: _candidates;
|
||||||
|
var weighted = eligible.Select(student =>
|
||||||
|
{
|
||||||
|
var weight = 1.0 / (1.0 + 1.5 * _drawCounts.GetValueOrDefault(student.Id));
|
||||||
|
if (ConsiderParticipation && _signals.TryGetValue(student.Id, out var signal))
|
||||||
|
{
|
||||||
|
var activityRatio = signal.Activity / (double)maxActivity;
|
||||||
|
weight *= 1.65 - activityRatio; // wenig Aktive werden wahrscheinlicher gezogen
|
||||||
|
if (signal.AverageRating is { } rating)
|
||||||
|
weight *= 1.0 - Math.Clamp(rating, -2, 2) * 0.175; // starke spaeter, schwache frueher
|
||||||
|
}
|
||||||
|
return (Student: student, Weight: Math.Max(0.01, weight));
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
|
var point = _random.NextDouble() * weighted.Sum(x => x.Weight);
|
||||||
|
foreach (var item in weighted)
|
||||||
|
{
|
||||||
|
point -= item.Weight;
|
||||||
|
if (point <= 0) return item.Student;
|
||||||
|
}
|
||||||
|
return weighted[^1].Student;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ResetDrawState()
|
||||||
|
{
|
||||||
|
_roundBag.Clear();
|
||||||
|
_drawCounts.Clear();
|
||||||
|
_lastStudentId = null;
|
||||||
|
HasDrawnStudent = false;
|
||||||
|
SelectedStudentName = "Bereit?";
|
||||||
|
UpdateStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateStatus()
|
||||||
|
{
|
||||||
|
StatusText = _candidates.Count switch
|
||||||
|
{
|
||||||
|
0 when SelectedGroup is null => "Wähle in den Optionen eine Lerngruppe.",
|
||||||
|
0 => "In dieser Lerngruppe sind heute keine aktiven Schüler.",
|
||||||
|
_ when !HasDrawnStudent => $"{_candidates.Count} Schüler stehen zur Auswahl.",
|
||||||
|
_ when !IsIntelligent && _roundBag.Count == 0 => "Alle waren dran. Der nächste Zug startet eine neue Runde.",
|
||||||
|
_ when !IsIntelligent => $"Noch {_roundBag.Count} bis zur nächsten Runde.",
|
||||||
|
_ => "Nächste Ziehung bereit.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record ParticipationSignal(int Activity, double? AverageRating);
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||||||
|
using CommunityToolkit.Mvvm.Input;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
/// Ein Zwischenstand-Durchgang: Stichtag und Anlass gelten für alle gewählten Schüler.
|
||||||
|
public sealed record InterimRunOptions(DateOnly Date, string Occasion, IReadOnlyCollection<Guid> StudentIds);
|
||||||
|
|
||||||
|
// ── Zwischenstand-Modus des Assistenten (2.7.5) ──────────────────────────────
|
||||||
|
//
|
||||||
|
// Mit InterimRunOptions gestartet, geht der Assistent nur die gewählten Schüler durch und
|
||||||
|
// notiert je Schüler eine vorläufige schriftliche, mündliche und Gesamtnote zum Stichtag —
|
||||||
|
// als InterimGrade, ohne die Zeugnisnote (ReportGrade) anzufassen. Vorgeschlagen wird der
|
||||||
|
// Stand aus InterimGradeCalculator, also inklusive des laufenden Mitarbeits-Abschnitts.
|
||||||
|
public partial class ReportGradeAssistantViewModel
|
||||||
|
{
|
||||||
|
[ObservableProperty] private string? _interimWritten;
|
||||||
|
[ObservableProperty] private string? _interimOral;
|
||||||
|
[ObservableProperty] private string? _interimOverall;
|
||||||
|
[ObservableProperty] private string? _interimNote;
|
||||||
|
[ObservableProperty] private string _interimWrittenError = "";
|
||||||
|
[ObservableProperty] private string _interimOralError = "";
|
||||||
|
[ObservableProperty] private string _interimOverallError = "";
|
||||||
|
[ObservableProperty] private bool _hasInterimEntry;
|
||||||
|
|
||||||
|
/// Alle bisher notierten Zwischenstände des gewählten Schülers — in beiden Modi sichtbar.
|
||||||
|
public ObservableCollection<AssistantInterimRow> InterimEntries { get; } = [];
|
||||||
|
public bool HasInterimEntries => InterimEntries.Count > 0;
|
||||||
|
|
||||||
|
public bool IsInterimMode => _interim is not null;
|
||||||
|
public bool IsReportMode => _interim is null;
|
||||||
|
public string WindowTitle => IsInterimMode ? "Zwischenstand" : "Zeugnisnoten-Assistent";
|
||||||
|
public string InterimTitle => _interim is null
|
||||||
|
? "" : $"Zwischenstand {_interim.Date:dd.MM.yyyy} · {_interim.Occasion}";
|
||||||
|
|
||||||
|
/// Startet aus dem Zeugnisnoten-Modus einen Zwischenstand für den gezeigten Schüler; vom
|
||||||
|
/// Fenster gesetzt, das den Startdialog öffnen kann.
|
||||||
|
public Func<Guid, Task>? OnStartInterim { get; set; }
|
||||||
|
|
||||||
|
private InterimGrade? CurrentInterim(Guid studentId) => _interim is null ? null
|
||||||
|
: _interimGrades.GetByStudentAndGroup(studentId, _groupId)
|
||||||
|
.FirstOrDefault(g => g.Date == _interim.Date && g.Occasion == _interim.Occasion);
|
||||||
|
|
||||||
|
private void RefreshInterimItem(AssistantStudentItem item)
|
||||||
|
{
|
||||||
|
var existing = CurrentInterim(item.StudentId);
|
||||||
|
if (existing is not null)
|
||||||
|
item.Update(existing.OverallValue, AssistantGradeStatus.Noted);
|
||||||
|
else
|
||||||
|
item.Update(_interimCalculator.Calculate(item.StudentId, _interim!.Date, RoundingRule).Result.Rounded ?? "–",
|
||||||
|
AssistantGradeStatus.Open);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ShowInterim(Guid studentId)
|
||||||
|
{
|
||||||
|
var interim = _interimCalculator.Calculate(studentId, _interim!.Date, RoundingRule);
|
||||||
|
var result = interim.Result;
|
||||||
|
|
||||||
|
_calculatedValue = result.Rounded;
|
||||||
|
CalculatedDisplay = result.Rounded ?? "–";
|
||||||
|
var between = result.Value is { } value ? ReportGradeCalculator.BetweenGrades(value) : null;
|
||||||
|
BorderlineHint = between is null ? "" : $"Liegt genau {between} — pädagogische Entscheidung.";
|
||||||
|
CalculationDetail = result.Value is null
|
||||||
|
? "Noch keine Leistungen bis zum Stichtag."
|
||||||
|
: $"Stand {_interim.Date:dd.MM.yyyy} · gewichtet {Format(result.Value.Value)} vor Rundung";
|
||||||
|
|
||||||
|
var scheme = _calculator.Scheme;
|
||||||
|
Tiles.Clear();
|
||||||
|
Tiles.Add(BucketTile("Schriftlich", result.Written, scheme.ExamsPercent));
|
||||||
|
Tiles.Add(new AssistantTile("Mitarbeit",
|
||||||
|
result.Participation.HasValue ? Format(result.Participation.Value) : "–",
|
||||||
|
$"{scheme.ParticipationPercent:0.#} %" +
|
||||||
|
(interim.RunningParticipation is null ? "" : $" · laufender Abschnitt: {interim.RunningParticipation}")));
|
||||||
|
Tiles.Add(BucketTile("Sonstige", result.Other, scheme.OtherPercent));
|
||||||
|
|
||||||
|
// Bereits notiert: der notierte Stand gilt. Sonst der berechnete Vorschlag zum Anpassen.
|
||||||
|
var existing = CurrentInterim(studentId);
|
||||||
|
HasInterimEntry = existing is not null;
|
||||||
|
InterimWritten = existing is not null ? existing.WrittenValue : RoundOrNull(result.Written);
|
||||||
|
InterimOral = existing is not null ? existing.OralValue : RoundOrNull(result.Participation);
|
||||||
|
InterimOverall = existing is not null ? existing.OverallValue : result.Rounded;
|
||||||
|
InterimNote = existing?.Note;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string? RoundOrNull(double? value) => value.HasValue ? _calculator.Round(value.Value, RoundingRule) : null;
|
||||||
|
|
||||||
|
private void LoadInterimEntries(Guid studentId)
|
||||||
|
{
|
||||||
|
InterimEntries.Clear();
|
||||||
|
foreach (var entry in _interimGrades.GetByStudentAndGroup(studentId, _groupId)
|
||||||
|
.OrderByDescending(g => g.Date).ThenByDescending(g => g.UpdatedAt))
|
||||||
|
InterimEntries.Add(new AssistantInterimRow(entry));
|
||||||
|
OnPropertyChanged(nameof(HasInterimEntries));
|
||||||
|
}
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void NoteInterim() => TryNoteInterim();
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void NoteInterimAndNext()
|
||||||
|
{
|
||||||
|
if (!TryNoteInterim()) return;
|
||||||
|
if (CanGoNextStudent) NextStudent();
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryNoteInterim()
|
||||||
|
{
|
||||||
|
if (_interim is null || SelectedStudent is null) return false;
|
||||||
|
ClearErrors();
|
||||||
|
var valid = true;
|
||||||
|
if (!IsGradeOrEmpty(InterimWritten)) { InterimWrittenError = "Keine gültige Note."; valid = false; }
|
||||||
|
if (!IsGradeOrEmpty(InterimOral)) { InterimOralError = "Keine gültige Note."; valid = false; }
|
||||||
|
if (NullIfEmpty(InterimOverall) is null) { InterimOverallError = "Gesamtnote erforderlich."; valid = false; }
|
||||||
|
else if (!IsGradeOrEmpty(InterimOverall)) { InterimOverallError = "Keine gültige Note."; valid = false; }
|
||||||
|
if (!valid) return false;
|
||||||
|
|
||||||
|
var studentId = SelectedStudent.StudentId;
|
||||||
|
var entry = CurrentInterim(studentId) ?? new InterimGrade
|
||||||
|
{
|
||||||
|
StudentId = studentId, GroupId = _groupId, Date = _interim.Date, Occasion = _interim.Occasion,
|
||||||
|
};
|
||||||
|
entry.WrittenValue = NullIfEmpty(InterimWritten);
|
||||||
|
entry.OralValue = NullIfEmpty(InterimOral);
|
||||||
|
entry.OverallValue = NullIfEmpty(InterimOverall)!;
|
||||||
|
entry.Note = NullIfEmpty(InterimNote);
|
||||||
|
_interimGrades.Save(entry);
|
||||||
|
|
||||||
|
RefreshItem(SelectedStudent);
|
||||||
|
ShowStudent();
|
||||||
|
StatusMessage = "Zwischenstand notiert.";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void RemoveInterim()
|
||||||
|
{
|
||||||
|
if (SelectedStudent is null || CurrentInterim(SelectedStudent.StudentId) is not { } entry) return;
|
||||||
|
_interimGrades.Delete(entry.Id);
|
||||||
|
RefreshItem(SelectedStudent);
|
||||||
|
ShowStudent();
|
||||||
|
StatusMessage = "Zwischenstand entfernt.";
|
||||||
|
}
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private async Task StartInterim()
|
||||||
|
{
|
||||||
|
if (OnStartInterim is null || SelectedStudent is null) return;
|
||||||
|
await OnStartInterim(SelectedStudent.StudentId);
|
||||||
|
ShowStudent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AssistantInterimRow(InterimGrade entry)
|
||||||
|
{
|
||||||
|
public string Title { get; } = $"{entry.Date:dd.MM.yyyy} · {entry.Occasion}";
|
||||||
|
public string OverallValue { get; } = entry.OverallValue;
|
||||||
|
public string Detail { get; } = string.Join(" · ", new[]
|
||||||
|
{
|
||||||
|
entry.WrittenValue is null ? null : $"schriftlich {entry.WrittenValue}",
|
||||||
|
entry.OralValue is null ? null : $"mündlich {entry.OralValue}",
|
||||||
|
}.Where(part => part is not null));
|
||||||
|
public string Note { get; } = entry.Note ?? "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,692 @@
|
|||||||
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||||||
|
using CommunityToolkit.Mvvm.Input;
|
||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
// ── Zeugnisnoten-Assistent ───────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// Geht die Lerngruppe Schüler für Schüler durch und zieht alles zusammen, was für die
|
||||||
|
// Halbjahres- bzw. Endjahresnote zählt: berechnete Note mit Teilbereichen, Mitarbeitsgraph
|
||||||
|
// (abschnittsweise blätterbar oder als durchgehender Verlauf), Arbeiten und Einzelnoten.
|
||||||
|
// Ergänzt den Zeugnisnoten-Dialog (2.4), ersetzt ihn nicht — beide schreiben dieselben
|
||||||
|
// ReportGrade-Datensätze (gleiche Period-Bezeichnungen), der Dialog bleibt die schnelle Liste.
|
||||||
|
//
|
||||||
|
// Halbjahre sind eigenständig: Leistungen aus dem 1. Halbjahr zählen nicht in die Note des
|
||||||
|
// 2. Halbjahrs, werden dort aber ausgegraut als Kontext gezeigt (Trends). Die Endjahresnote
|
||||||
|
// wird aus den Halbjahresnoten verrechnet, nicht aus allen Einzelleistungen; in Klasse 10 lassen
|
||||||
|
// sich dafür zusätzlich Projekt- und mündliche Prüfung eintragen (siehe ReportGradeCalculator).
|
||||||
|
public partial class ReportGradeAssistantViewModel : ObservableObject
|
||||||
|
{
|
||||||
|
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
|
||||||
|
|
||||||
|
private const int ExamGradeLevel = 10;
|
||||||
|
|
||||||
|
private readonly IReportGradeRepository _reportGrades;
|
||||||
|
private readonly IParticipationRepository _participation;
|
||||||
|
private readonly AttendanceBalanceService _attendanceBalance;
|
||||||
|
private readonly GradingService _grading;
|
||||||
|
private readonly ParticipationTimelineBuilder _timeline;
|
||||||
|
private readonly ReportGradeCalculator _calculator;
|
||||||
|
private readonly InterimGradeCalculator _interimCalculator;
|
||||||
|
private readonly IInterimGradeRepository _interimGrades;
|
||||||
|
private readonly InterimRunOptions? _interim;
|
||||||
|
private readonly Guid _groupId;
|
||||||
|
private readonly int _gradeLevel;
|
||||||
|
private readonly DateOnly _today;
|
||||||
|
|
||||||
|
private readonly List<Student> _allStudents;
|
||||||
|
private readonly Dictionary<Guid, GroupMembership> _membershipsByStudent;
|
||||||
|
private readonly List<ParticipationSection> _sections;
|
||||||
|
|
||||||
|
private string? _calculatedValue;
|
||||||
|
private bool _showing;
|
||||||
|
private List<SectionView> _sectionViews = [];
|
||||||
|
private int _sectionIndex;
|
||||||
|
private bool _loading;
|
||||||
|
|
||||||
|
public string GroupLabel { get; }
|
||||||
|
|
||||||
|
[ObservableProperty] private ParticipationPeriodOption _selectedPeriod;
|
||||||
|
[ObservableProperty] private RoundingRule _roundingRule = RoundingRule.Commercial;
|
||||||
|
[ObservableProperty] private string _schemeSummary = "";
|
||||||
|
[ObservableProperty] private AssistantStudentItem? _selectedStudent;
|
||||||
|
[ObservableProperty] private bool _showPreviousHalf = true;
|
||||||
|
|
||||||
|
// Kopf: Note des gewählten Schülers
|
||||||
|
[ObservableProperty] private string _calculatedDisplay = "–";
|
||||||
|
[ObservableProperty] private string _calculationDetail = "";
|
||||||
|
[ObservableProperty] private string _borderlineHint = "";
|
||||||
|
[ObservableProperty] private string _absenceRateDisplay = "";
|
||||||
|
[ObservableProperty] private string _absenceRateColorHex = "#8A8A8A";
|
||||||
|
[ObservableProperty] private string? _overrideValue;
|
||||||
|
[ObservableProperty] private string? _overrideReason;
|
||||||
|
[ObservableProperty] private string _overrideReasonError = "";
|
||||||
|
[ObservableProperty] private bool _isLocked;
|
||||||
|
[ObservableProperty] private string _statusMessage = "";
|
||||||
|
|
||||||
|
// Klasse 10: Prüfungsnoten, die in der Endjahresnote wie ein weiteres Halbjahr zählen
|
||||||
|
[ObservableProperty] private string? _projectExamGrade;
|
||||||
|
[ObservableProperty] private string? _oralExamGrade;
|
||||||
|
[ObservableProperty] private string? _writtenExamGrade;
|
||||||
|
[ObservableProperty] private string? _additionalOralExamGrade;
|
||||||
|
[ObservableProperty] private string _projectExamGradeError = "";
|
||||||
|
[ObservableProperty] private string _oralExamGradeError = "";
|
||||||
|
[ObservableProperty] private string _writtenExamGradeError = "";
|
||||||
|
[ObservableProperty] private string _additionalOralExamGradeError = "";
|
||||||
|
|
||||||
|
// Mitarbeitsgraph
|
||||||
|
[ObservableProperty] private bool _isSectionMode = true;
|
||||||
|
[ObservableProperty] private double _timelineZoom = 1.0;
|
||||||
|
[ObservableProperty] private IReadOnlyList<WizardSectionGroup> _chartGroups = [];
|
||||||
|
[ObservableProperty] private string _sectionTitle = "";
|
||||||
|
[ObservableProperty] private string _sectionPosition = "";
|
||||||
|
|
||||||
|
public List<ParticipationPeriodOption> PeriodOptions { get; } =
|
||||||
|
[
|
||||||
|
new(ParticipationPeriod.H1, "1. Halbjahr"),
|
||||||
|
new(ParticipationPeriod.H2, "2. Halbjahr"),
|
||||||
|
new(ParticipationPeriod.FullYear, "Gesamtes Schuljahr"),
|
||||||
|
];
|
||||||
|
public string[] RoundingOptions { get; } = RoundingRuleDisplay.Options;
|
||||||
|
|
||||||
|
// Für die ComboBox: deutsche Anzeige statt des rohen Enum-Namens.
|
||||||
|
public string RoundingRuleName
|
||||||
|
{
|
||||||
|
get => RoundingRuleDisplay.Label(RoundingRule);
|
||||||
|
set => RoundingRule = RoundingRuleDisplay.FromLabel(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObservableCollection<AssistantStudentItem> Students { get; } = [];
|
||||||
|
public ObservableCollection<AssistantTile> Tiles { get; } = [];
|
||||||
|
public ObservableCollection<AssistantWorkCard> Works { get; } = [];
|
||||||
|
public ObservableCollection<AssistantGradeRow> ParticipationGrades { get; } = [];
|
||||||
|
public ObservableCollection<AssistantGradeRow> OtherGrades { get; } = [];
|
||||||
|
|
||||||
|
public bool HasStudent => SelectedStudent is not null;
|
||||||
|
public string StudentName => SelectedStudent?.Name ?? "";
|
||||||
|
public string ProgressText => SelectedStudent is null
|
||||||
|
? "" : $"{Students.IndexOf(SelectedStudent) + 1} / {Students.Count}";
|
||||||
|
public string LockLabel => IsLocked ? "Entsperren" : "Festschreiben";
|
||||||
|
public string FinalDisplay => !string.IsNullOrWhiteSpace(OverrideValue) ? OverrideValue!.Trim() : CalculatedDisplay;
|
||||||
|
public bool IsContinuousMode => !IsSectionMode;
|
||||||
|
/// Nur im 2. Halbjahr gibt es ein Vorhalbjahr, das als Kontext eingeblendet werden kann.
|
||||||
|
public bool CanShowPreviousHalf => SelectedPeriod.Period == ParticipationPeriod.H2;
|
||||||
|
/// Projekt- und mündliche Prüfung gibt es nur in Klasse 10 und nur für die Endjahresnote.
|
||||||
|
public bool CanEnterExamGrades =>
|
||||||
|
SelectedPeriod.Period == ParticipationPeriod.FullYear && _gradeLevel == ExamGradeLevel;
|
||||||
|
public bool HasWorks => Works.Count > 0;
|
||||||
|
public bool HasParticipationGrades => ParticipationGrades.Count > 0;
|
||||||
|
public bool HasOtherGrades => OtherGrades.Count > 0;
|
||||||
|
|
||||||
|
public ReportGradeAssistantViewModel(IGradeRepository grades, IExamRepository exams,
|
||||||
|
IExamResultRepository results, IStudentRepository students, IGroupMembershipRepository memberships,
|
||||||
|
IGradingSchemeRepository schemes, IReportGradeRepository reportGrades,
|
||||||
|
IParticipationSessionRepository participationSessions, IParticipationRepository participation,
|
||||||
|
IParticipationAspectRepository aspects, IParticipationSectionRepository sections,
|
||||||
|
IInterimGradeRepository interimGrades,
|
||||||
|
AttendanceBalanceService attendanceBalance, GradingService grading,
|
||||||
|
Guid groupId, GroupType groupType, GradingSystem gradingSystem, string groupLabel, string schoolYear,
|
||||||
|
int gradeLevel, DateOnly? today = null, InterimRunOptions? interim = null)
|
||||||
|
{
|
||||||
|
_reportGrades = reportGrades; _participation = participation;
|
||||||
|
_interimGrades = interimGrades; _interim = interim;
|
||||||
|
_attendanceBalance = attendanceBalance; _grading = grading;
|
||||||
|
_groupId = groupId; _gradeLevel = gradeLevel;
|
||||||
|
_today = today ?? DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
GroupLabel = groupLabel;
|
||||||
|
|
||||||
|
_membershipsByStudent = memberships.GetByGroup(groupId).ToDictionary(m => m.StudentId);
|
||||||
|
_allStudents = students.GetByGroup(groupId).OrderBy(s => s.LastName).ThenBy(s => s.FirstName).ToList();
|
||||||
|
_sections = sections.GetByGroup(groupId).OrderBy(s => s.StartDate).ToList();
|
||||||
|
_timeline = new ParticipationTimelineBuilder(participationSessions, participation, aspects, exams, results,
|
||||||
|
grades, _membershipsByStudent, grading, groupId, gradingSystem);
|
||||||
|
_calculator = new ReportGradeCalculator(grades, exams, results, schemes, reportGrades,
|
||||||
|
_membershipsByStudent, grading, groupId, groupType, gradingSystem, schoolYear);
|
||||||
|
|
||||||
|
_interimCalculator = new InterimGradeCalculator(_calculator, _timeline, _sections);
|
||||||
|
|
||||||
|
// Vorbelegung: das Halbjahr, in dem wir uns gerade befinden — bzw. das des Stichtags.
|
||||||
|
var half = _interimCalculator.HalfOf(_interim?.Date ?? _today);
|
||||||
|
_selectedPeriod = PeriodOptions.First(p => p.Period == half);
|
||||||
|
Reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnSelectedPeriodChanged(ParticipationPeriodOption value)
|
||||||
|
{
|
||||||
|
OnPropertyChanged(nameof(CanShowPreviousHalf));
|
||||||
|
OnPropertyChanged(nameof(CanEnterExamGrades));
|
||||||
|
Reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnRoundingRuleChanged(RoundingRule value) => Reload();
|
||||||
|
partial void OnShowPreviousHalfChanged(bool value) => ShowStudent();
|
||||||
|
|
||||||
|
partial void OnSelectedStudentChanged(AssistantStudentItem? value)
|
||||||
|
{
|
||||||
|
OnPropertyChanged(nameof(HasStudent));
|
||||||
|
OnPropertyChanged(nameof(StudentName));
|
||||||
|
OnPropertyChanged(nameof(ProgressText));
|
||||||
|
PreviousStudentCommand.NotifyCanExecuteChanged();
|
||||||
|
NextStudentCommand.NotifyCanExecuteChanged();
|
||||||
|
if (!_loading) ShowStudent();
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnIsSectionModeChanged(bool value)
|
||||||
|
{
|
||||||
|
OnPropertyChanged(nameof(IsContinuousMode));
|
||||||
|
ApplyChartMode();
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnIsLockedChanged(bool value) => OnPropertyChanged(nameof(LockLabel));
|
||||||
|
partial void OnOverrideValueChanged(string? value) => OnPropertyChanged(nameof(FinalDisplay));
|
||||||
|
partial void OnCalculatedDisplayChanged(string value) => OnPropertyChanged(nameof(FinalDisplay));
|
||||||
|
|
||||||
|
// Eine eingetippte Prüfungsnote wirkt sofort auf die angezeigte Berechnung, gespeichert wird
|
||||||
|
// sie erst mit der Zeugnisnote.
|
||||||
|
partial void OnProjectExamGradeChanged(string? value) { if (!_showing) ShowCalculation(); }
|
||||||
|
partial void OnOralExamGradeChanged(string? value) { if (!_showing) ShowCalculation(); }
|
||||||
|
partial void OnWrittenExamGradeChanged(string? value) { if (!_showing) ShowCalculation(); }
|
||||||
|
partial void OnAdditionalOralExamGradeChanged(string? value) { if (!_showing) ShowCalculation(); }
|
||||||
|
|
||||||
|
private void ClearErrors()
|
||||||
|
{
|
||||||
|
OverrideReasonError = ""; ProjectExamGradeError = ""; OralExamGradeError = "";
|
||||||
|
WrittenExamGradeError = ""; AdditionalOralExamGradeError = "";
|
||||||
|
InterimWrittenError = ""; InterimOralError = ""; InterimOverallError = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Laden ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private void Reload()
|
||||||
|
{
|
||||||
|
_calculator.Reload();
|
||||||
|
SchemeSummary = _calculator.SchemeSummary;
|
||||||
|
|
||||||
|
var (from, to) = _calculator.Range(SelectedPeriod.Period);
|
||||||
|
var previousId = SelectedStudent?.StudentId;
|
||||||
|
|
||||||
|
_loading = true;
|
||||||
|
Students.Clear();
|
||||||
|
foreach (var student in _allStudents)
|
||||||
|
{
|
||||||
|
if (_interim is not null && !_interim.StudentIds.Contains(student.Id)) continue;
|
||||||
|
if (_membershipsByStudent.TryGetValue(student.Id, out var membership)
|
||||||
|
&& !GroupMembershipService.Overlaps(membership, from, to)) continue;
|
||||||
|
var item = new AssistantStudentItem(student.Id, student.FullName);
|
||||||
|
RefreshItem(item);
|
||||||
|
Students.Add(item);
|
||||||
|
}
|
||||||
|
SelectedStudent = Students.FirstOrDefault(s => s.StudentId == previousId) ?? Students.FirstOrDefault();
|
||||||
|
_loading = false;
|
||||||
|
|
||||||
|
OnPropertyChanged(nameof(ProgressText));
|
||||||
|
PreviousStudentCommand.NotifyCanExecuteChanged();
|
||||||
|
NextStudentCommand.NotifyCanExecuteChanged();
|
||||||
|
ShowStudent();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshItem(AssistantStudentItem item)
|
||||||
|
{
|
||||||
|
if (_interim is not null) { RefreshInterimItem(item); return; }
|
||||||
|
var record = _reportGrades.GetByStudentGroupPeriod(item.StudentId, _groupId, SelectedPeriod.Label);
|
||||||
|
var calculated = record is { IsLocked: true }
|
||||||
|
? NullIfEmpty(record.CalculatedValue)
|
||||||
|
: _calculator.Calculate(item.StudentId, SelectedPeriod.Period, RoundingRule).Rounded;
|
||||||
|
item.Update(NullIfEmpty(record?.OverrideValue) ?? calculated ?? "–", record switch
|
||||||
|
{
|
||||||
|
null => AssistantGradeStatus.Open,
|
||||||
|
{ IsLocked: true } => AssistantGradeStatus.Locked,
|
||||||
|
_ => AssistantGradeStatus.Saved,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Berechnung ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// ── Anzeige des gewählten Schülers ───────────────────────────────────────
|
||||||
|
|
||||||
|
private void ShowStudent()
|
||||||
|
{
|
||||||
|
StatusMessage = "";
|
||||||
|
ClearErrors();
|
||||||
|
Works.Clear(); ParticipationGrades.Clear(); OtherGrades.Clear();
|
||||||
|
|
||||||
|
if (SelectedStudent is null)
|
||||||
|
{
|
||||||
|
_calculatedValue = null;
|
||||||
|
Tiles.Clear();
|
||||||
|
CalculatedDisplay = "–"; CalculationDetail = ""; BorderlineHint = ""; AbsenceRateDisplay = "";
|
||||||
|
OverrideValue = null; OverrideReason = null; IsLocked = false;
|
||||||
|
InterimEntries.Clear();
|
||||||
|
OnPropertyChanged(nameof(HasInterimEntries));
|
||||||
|
_sectionViews = [];
|
||||||
|
ApplyChartMode();
|
||||||
|
NotifyLists();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var studentId = SelectedStudent.StudentId;
|
||||||
|
var (from, to) = _calculator.Range(SelectedPeriod.Period);
|
||||||
|
// Zwischenstand: alles nach dem Stichtag bleibt außen vor, auch in der Anzeige.
|
||||||
|
if (_interim is not null && _interim.Date < to) to = _interim.Date;
|
||||||
|
_membershipsByStudent.TryGetValue(studentId, out var membership);
|
||||||
|
|
||||||
|
var record = _interim is null
|
||||||
|
? _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, SelectedPeriod.Label) : null;
|
||||||
|
_showing = true;
|
||||||
|
IsLocked = record is { IsLocked: true };
|
||||||
|
OverrideValue = record?.OverrideValue;
|
||||||
|
OverrideReason = record?.OverrideReason;
|
||||||
|
ProjectExamGrade = CanEnterExamGrades ? record?.ProjectExamGrade : null;
|
||||||
|
OralExamGrade = CanEnterExamGrades ? record?.OralExamGrade : null;
|
||||||
|
WrittenExamGrade = CanEnterExamGrades ? record?.WrittenExamGrade : null;
|
||||||
|
AdditionalOralExamGrade = CanEnterExamGrades ? record?.AdditionalOralExamGrade : null;
|
||||||
|
_showing = false;
|
||||||
|
|
||||||
|
if (_interim is not null) ShowInterim(studentId); else ShowCalculation();
|
||||||
|
LoadInterimEntries(studentId);
|
||||||
|
ShowAbsenceRate(studentId, from, to);
|
||||||
|
|
||||||
|
// Im 2. Halbjahr auf Wunsch das Vorhalbjahr als Kontext mitzeigen — ohne Einfluss auf die Note.
|
||||||
|
var displayFrom = CanShowPreviousHalf && ShowPreviousHalf
|
||||||
|
? _calculator.Range(ParticipationPeriod.FullYear).From : from;
|
||||||
|
BuildWorks(studentId, membership, displayFrom, from, to);
|
||||||
|
BuildGradeRows(studentId, membership, displayFrom, from, to);
|
||||||
|
BuildSections(studentId, displayFrom, to);
|
||||||
|
NotifyLists();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Berechnete Note und Teilnoten-Kacheln des gewählten Schülers.
|
||||||
|
private void ShowCalculation()
|
||||||
|
{
|
||||||
|
if (SelectedStudent is null) return;
|
||||||
|
var studentId = SelectedStudent.StudentId;
|
||||||
|
var period = SelectedPeriod.Period;
|
||||||
|
// In Klasse 10 gelten die gerade eingetragenen Prüfungsnoten, sonst die gespeicherten.
|
||||||
|
YearExamGrades? typed = CanEnterExamGrades
|
||||||
|
? new YearExamGrades(ProjectExamGrade, OralExamGrade, WrittenExamGrade, AdditionalOralExamGrade)
|
||||||
|
: null;
|
||||||
|
var result = _calculator.Calculate(studentId, period, RoundingRule, typed);
|
||||||
|
|
||||||
|
// Festgeschrieben heißt: der gespeicherte Stand gilt, es wird nicht neu berechnet.
|
||||||
|
_calculatedValue = IsLocked
|
||||||
|
? NullIfEmpty(_reportGrades.GetByStudentGroupPeriod(studentId, _groupId, SelectedPeriod.Label)?.CalculatedValue)
|
||||||
|
: result.Rounded;
|
||||||
|
CalculatedDisplay = _calculatedValue ?? "–";
|
||||||
|
// Genau auf der Grenze entscheidet die gewählte Rundung nur formal — der Hinweis macht
|
||||||
|
// sichtbar, dass hier die Lehrkraft entscheiden sollte.
|
||||||
|
var between = !IsLocked && result.Value is { } value ? ReportGradeCalculator.BetweenGrades(value) : null;
|
||||||
|
BorderlineHint = between is null ? "" : $"Liegt genau {between} — pädagogische Entscheidung.";
|
||||||
|
|
||||||
|
Tiles.Clear();
|
||||||
|
if (period == ParticipationPeriod.FullYear)
|
||||||
|
{
|
||||||
|
var parts = _calculator.YearParts(studentId, RoundingRule, typed);
|
||||||
|
foreach (var part in parts)
|
||||||
|
Tiles.Add(new AssistantTile(part.Label, part.Final ?? "–", part.Hint));
|
||||||
|
CalculationDetail = result.Value is null
|
||||||
|
? "Noch keine Halbjahresnote vorhanden."
|
||||||
|
: $"aus {parts.Count(p => p.Final is not null)} Teilnoten {Format(result.Value.Value)} vor Rundung";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var scheme = _calculator.Scheme;
|
||||||
|
Tiles.Add(BucketTile("Schriftlich", result.Written, scheme.ExamsPercent));
|
||||||
|
Tiles.Add(BucketTile("Mitarbeit", result.Participation, scheme.ParticipationPercent));
|
||||||
|
Tiles.Add(BucketTile("Sonstige", result.Other, scheme.OtherPercent));
|
||||||
|
CalculationDetail = result.Value is null
|
||||||
|
? "Noch keine Leistungen im gewählten Zeitraum."
|
||||||
|
: $"gewichtet {Format(result.Value.Value)} vor Rundung";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void NotifyLists()
|
||||||
|
{
|
||||||
|
OnPropertyChanged(nameof(HasWorks));
|
||||||
|
OnPropertyChanged(nameof(HasParticipationGrades));
|
||||||
|
OnPropertyChanged(nameof(HasOtherGrades));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AssistantTile BucketTile(string label, double? average, double percent) =>
|
||||||
|
new(label, average.HasValue ? Format(average.Value) : "–", $"{percent:0.#} %");
|
||||||
|
|
||||||
|
private void ShowAbsenceRate(Guid studentId, DateOnly from, DateOnly to)
|
||||||
|
{
|
||||||
|
// Wie im Zeugnisnoten-Dialog (2.4.5): nur Sitzungen dieser Gruppe im gewählten Zeitraum.
|
||||||
|
var attendance = _timeline.Sessions
|
||||||
|
.Where(s => s.Date >= from && s.Date <= to)
|
||||||
|
.Select(s => (s.Date, _participation.GetBySessionAndStudent(s.Id, studentId)?.Attendance))
|
||||||
|
.ToList();
|
||||||
|
var rate = _attendanceBalance.Calculate(attendance, from, to).AbsenceRatePercent;
|
||||||
|
AbsenceRateDisplay = $"{rate:0.#} % gefehlt";
|
||||||
|
AbsenceRateColorHex = rate >= ReportGradeRow.HighAbsenceThresholdPercent ? "#D64545" : "#8A8A8A";
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BuildWorks(Guid studentId, GroupMembership? membership, DateOnly displayFrom, DateOnly from, DateOnly to)
|
||||||
|
{
|
||||||
|
foreach (var exam in _calculator.Exams.Where(e => e.Date >= displayFrom && e.Date <= to))
|
||||||
|
{
|
||||||
|
if (!ReportGradeCalculator.ExamApplies(exam, membership)) continue;
|
||||||
|
var results = _calculator.ResultsByExam[exam.Id];
|
||||||
|
results.TryGetValue(studentId, out var own);
|
||||||
|
// Nachschreib-, Förder- und Wiederholungsarbeiten betreffen nur einzelne Schüler — ohne eigenes
|
||||||
|
// Ergebnis gehören sie nicht in diese Übersicht.
|
||||||
|
if (own is null && exam.RepeatOfExamId.HasValue) continue;
|
||||||
|
|
||||||
|
var gradeDisplay = own switch
|
||||||
|
{
|
||||||
|
null => "–",
|
||||||
|
{ Absent: true } => "abw.",
|
||||||
|
_ => own.Grade ?? "–",
|
||||||
|
};
|
||||||
|
|
||||||
|
var percentDisplay = "";
|
||||||
|
if (own is { Absent: false })
|
||||||
|
{
|
||||||
|
var maximum = ExamScoringService.Maximum(exam.Tasks, own.Variant);
|
||||||
|
if (maximum > 0) percentDisplay = $"{own.TotalPoints / maximum * 100:0} %";
|
||||||
|
}
|
||||||
|
|
||||||
|
var classGrades = results.Values.Where(r => !r.Absent && r.Grade is not null)
|
||||||
|
.Select(r => (r.Grade!, 1.0)).ToList();
|
||||||
|
var classAverage = classGrades.Count > 0 ? $"Ø Kurs {Format(_grading.WeightedAverage(classGrades))}" : "";
|
||||||
|
|
||||||
|
var kind = exam.Kind.Label();
|
||||||
|
if (exam.IsSupportWork) kind += " · Förderarbeit";
|
||||||
|
else if (exam.IsMakeUp) kind += " · Nachschreibarbeit";
|
||||||
|
else if (exam.RepeatOfExamId.HasValue) kind += " · Wiederholung";
|
||||||
|
|
||||||
|
Works.Add(new AssistantWorkCard(exam.Title, exam.Date, kind, gradeDisplay, percentDisplay,
|
||||||
|
classAverage, isContext: exam.Date < from));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BuildGradeRows(Guid studentId, GroupMembership? membership, DateOnly displayFrom, DateOnly from, DateOnly to)
|
||||||
|
{
|
||||||
|
foreach (var grade in _calculator.Grades
|
||||||
|
.Where(g => g.StudentId == studentId && g.Date >= displayFrom && g.Date <= to)
|
||||||
|
.Where(g => membership is null || GroupMembershipService.IsActiveOn(membership, g.Date)))
|
||||||
|
{
|
||||||
|
var isParticipation = grade.Category == GradeCategory.Participation;
|
||||||
|
var category = GradeCategoryDisplay.Label(grade.Category);
|
||||||
|
var label = string.IsNullOrWhiteSpace(grade.Note)
|
||||||
|
? category
|
||||||
|
: isParticipation ? grade.Note.Trim() : $"{category}: {grade.Note.Trim()}";
|
||||||
|
var row = new AssistantGradeRow(label, grade.Date, grade.Value, isContext: grade.Date < from);
|
||||||
|
(isParticipation ? ParticipationGrades : OtherGrades).Add(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Mitarbeitsgraph: Abschnitte / Verlauf ────────────────────────────────
|
||||||
|
|
||||||
|
private sealed record SectionView(WizardSectionGroup Group, string Title);
|
||||||
|
|
||||||
|
private void BuildSections(Guid studentId, DateOnly displayFrom, DateOnly to)
|
||||||
|
{
|
||||||
|
var points = _timeline.BuildPoints(studentId).Where(p => p.Date >= displayFrom && p.Date <= to).ToList();
|
||||||
|
// Notierte Zwischenstände erscheinen als Marker im Verlauf.
|
||||||
|
points.AddRange(_interimGrades.GetByStudentAndGroup(studentId, _groupId)
|
||||||
|
.Where(g => g.Date >= displayFrom && g.Date <= to)
|
||||||
|
.Select(g => new WizardTimelinePoint(g.Date, isExam: true, ratingLabel: "",
|
||||||
|
examLabel: $"Zwischenstand: {g.OverallValue}", hasNote: false,
|
||||||
|
tooltip: $"{g.Date:dd.MM.yyyy} · {g.Occasion} · Zwischenstand {g.OverallValue}")));
|
||||||
|
points = points.OrderBy(p => p.Date).ToList();
|
||||||
|
var sectionGrades = _calculator.Grades
|
||||||
|
.Where(g => g.StudentId == studentId && g.Category == GradeCategory.Participation && g.Note is not null)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var views = new List<SectionView>();
|
||||||
|
foreach (var section in _sections.Where(s => s.EndDate >= displayFrom && s.StartDate <= to))
|
||||||
|
{
|
||||||
|
var group = new WizardSectionGroup(ParticipationTimelineBuilder.BandLabel(section), isOpen: false);
|
||||||
|
foreach (var point in points.Where(p => p.Date >= section.StartDate && p.Date <= section.EndDate))
|
||||||
|
group.Points.Add(point);
|
||||||
|
var grade = sectionGrades.FirstOrDefault(g =>
|
||||||
|
g.Note == ParticipationTimelineBuilder.SectionNotePrefix + section.Label)?.Value;
|
||||||
|
views.Add(new SectionView(group,
|
||||||
|
$"{section.Label} · {section.StartDate:dd.MM.}–{section.EndDate:dd.MM.} · " +
|
||||||
|
(grade is null ? "keine Abschnittsnote" : $"Abschnittsnote {grade}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Der laufende Abschnitt endet erst mit dem nächsten Abschluss im Mitarbeits-Assistenten;
|
||||||
|
// bis dahin gibt es nur einen Vorschlag aus den bisherigen Sitzungen.
|
||||||
|
var asOf = _interim?.Date ?? _today;
|
||||||
|
// Ohne jeden abgeschlossenen Abschnitt gehört der ganze Zeitraum zum laufenden — sonst
|
||||||
|
// fielen Arbeiten und Zwischenstände vor der ersten Mitarbeit-Sitzung aus dem Verlauf.
|
||||||
|
var openStart = _sections.Count == 0 ? displayFrom : _timeline.OpenStart(_sections, asOf);
|
||||||
|
if (openStart <= to)
|
||||||
|
{
|
||||||
|
var group = new WizardSectionGroup(ParticipationTimelineBuilder.OpenBandLabel(openStart), isOpen: true);
|
||||||
|
foreach (var point in points.Where(p => p.Date >= openStart))
|
||||||
|
group.Points.Add(point);
|
||||||
|
var end = asOf < to ? asOf : to;
|
||||||
|
var suggestion = _timeline.ComputeSuggestion(studentId, openStart < displayFrom ? displayFrom : openStart, end);
|
||||||
|
views.Add(new SectionView(group,
|
||||||
|
$"Laufender Abschnitt seit {openStart:dd.MM.} · " +
|
||||||
|
(suggestion is null ? "noch kein Vorschlag" : $"vorläufig {suggestion}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
_sectionViews = views;
|
||||||
|
// Beim Schülerwechsel im selben Abschnitt bleiben — so lassen sich Schüler abschnittsweise vergleichen.
|
||||||
|
_sectionIndex = Math.Clamp(_sectionIndex, 0, Math.Max(0, views.Count - 1));
|
||||||
|
ApplyChartMode();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ApplyChartMode()
|
||||||
|
{
|
||||||
|
if (_sectionViews.Count == 0)
|
||||||
|
{
|
||||||
|
ChartGroups = [];
|
||||||
|
SectionTitle = ""; SectionPosition = "";
|
||||||
|
}
|
||||||
|
else if (IsSectionMode)
|
||||||
|
{
|
||||||
|
var view = _sectionViews[_sectionIndex];
|
||||||
|
ChartGroups = [view.Group];
|
||||||
|
SectionTitle = view.Title;
|
||||||
|
SectionPosition = $"{_sectionIndex + 1} / {_sectionViews.Count}";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ChartGroups = _sectionViews.Select(v => v.Group).ToList();
|
||||||
|
SectionTitle = ""; SectionPosition = "";
|
||||||
|
}
|
||||||
|
PreviousSectionCommand.NotifyCanExecuteChanged();
|
||||||
|
NextSectionCommand.NotifyCanExecuteChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool CanGoPreviousSection => IsSectionMode && _sectionIndex > 0;
|
||||||
|
private bool CanGoNextSection => IsSectionMode && _sectionIndex < _sectionViews.Count - 1;
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanGoPreviousSection))]
|
||||||
|
private void PreviousSection() { _sectionIndex--; ApplyChartMode(); }
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanGoNextSection))]
|
||||||
|
private void NextSection() { _sectionIndex++; ApplyChartMode(); }
|
||||||
|
|
||||||
|
// ── Navigation ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private int StudentIndex => SelectedStudent is null ? -1 : Students.IndexOf(SelectedStudent);
|
||||||
|
private bool CanGoPreviousStudent => StudentIndex > 0;
|
||||||
|
private bool CanGoNextStudent => StudentIndex >= 0 && StudentIndex < Students.Count - 1;
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanGoPreviousStudent))]
|
||||||
|
private void PreviousStudent() => SelectedStudent = Students[StudentIndex - 1];
|
||||||
|
|
||||||
|
[RelayCommand(CanExecute = nameof(CanGoNextStudent))]
|
||||||
|
private void NextStudent() => SelectedStudent = Students[StudentIndex + 1];
|
||||||
|
|
||||||
|
// ── Speichern / Festschreiben ────────────────────────────────────────────
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void Save() => TrySave();
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void SaveAndNext()
|
||||||
|
{
|
||||||
|
if (!TrySave()) return;
|
||||||
|
if (CanGoNextStudent) NextStudent();
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TrySave()
|
||||||
|
{
|
||||||
|
if (SelectedStudent is null || IsLocked) return false;
|
||||||
|
ClearErrors();
|
||||||
|
var valid = true;
|
||||||
|
if (!string.IsNullOrWhiteSpace(OverrideValue) && string.IsNullOrWhiteSpace(OverrideReason))
|
||||||
|
{
|
||||||
|
OverrideReasonError = "Für ein manuelles Übersteuern ist eine Begründung Pflicht.";
|
||||||
|
valid = false;
|
||||||
|
}
|
||||||
|
if (CanEnterExamGrades)
|
||||||
|
{
|
||||||
|
if (!IsGradeOrEmpty(ProjectExamGrade)) { ProjectExamGradeError = "Keine gültige Note."; valid = false; }
|
||||||
|
if (!IsGradeOrEmpty(OralExamGrade)) { OralExamGradeError = "Keine gültige Note."; valid = false; }
|
||||||
|
if (!IsGradeOrEmpty(WrittenExamGrade)) { WrittenExamGradeError = "Keine gültige Note."; valid = false; }
|
||||||
|
if (!IsGradeOrEmpty(AdditionalOralExamGrade)) { AdditionalOralExamGradeError = "Keine gültige Note."; valid = false; }
|
||||||
|
|
||||||
|
// Ein Fach ist entweder schriftliches oder mündliches Prüfungsfach; eine zusätzliche
|
||||||
|
// mündliche Prüfung gibt es nur im schriftlichen Prüfungsfach oder ganz ohne Abschlussprüfung.
|
||||||
|
var hasOral = NullIfEmpty(OralExamGrade) is not null;
|
||||||
|
if (hasOral && NullIfEmpty(WrittenExamGrade) is not null)
|
||||||
|
{
|
||||||
|
OralExamGradeError = "Entweder schriftliche oder mündliche Abschlussprüfung.";
|
||||||
|
valid = false;
|
||||||
|
}
|
||||||
|
if (hasOral && NullIfEmpty(AdditionalOralExamGrade) is not null)
|
||||||
|
{
|
||||||
|
AdditionalOralExamGradeError = "Im Fach der mündlichen Abschlussprüfung nicht vorgesehen.";
|
||||||
|
valid = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!valid) return false;
|
||||||
|
|
||||||
|
var record = _reportGrades.GetByStudentGroupPeriod(SelectedStudent.StudentId, _groupId, SelectedPeriod.Label)
|
||||||
|
?? new ReportGrade { StudentId = SelectedStudent.StudentId, GroupId = _groupId, Period = SelectedPeriod.Label };
|
||||||
|
record.CalculatedValue = _calculatedValue ?? "";
|
||||||
|
record.OverrideValue = NullIfEmpty(OverrideValue);
|
||||||
|
record.OverrideReason = NullIfEmpty(OverrideReason);
|
||||||
|
if (CanEnterExamGrades)
|
||||||
|
{
|
||||||
|
record.ProjectExamGrade = NullIfEmpty(ProjectExamGrade);
|
||||||
|
record.OralExamGrade = NullIfEmpty(OralExamGrade);
|
||||||
|
record.WrittenExamGrade = NullIfEmpty(WrittenExamGrade);
|
||||||
|
record.AdditionalOralExamGrade = NullIfEmpty(AdditionalOralExamGrade);
|
||||||
|
}
|
||||||
|
record.UpdatedAt = DateTime.UtcNow;
|
||||||
|
_reportGrades.Save(record);
|
||||||
|
|
||||||
|
RefreshItem(SelectedStudent);
|
||||||
|
StatusMessage = "Gespeichert.";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private void ToggleLock()
|
||||||
|
{
|
||||||
|
if (SelectedStudent is null) return;
|
||||||
|
var studentId = SelectedStudent.StudentId;
|
||||||
|
var record = _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, SelectedPeriod.Label);
|
||||||
|
if (!IsLocked)
|
||||||
|
{
|
||||||
|
// Festschreiben sichert immer zuerst den aktuell angezeigten Stand.
|
||||||
|
if (!TrySave()) return;
|
||||||
|
record = _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, SelectedPeriod.Label);
|
||||||
|
}
|
||||||
|
if (record is null) return;
|
||||||
|
|
||||||
|
record.IsLocked = !record.IsLocked;
|
||||||
|
record.UpdatedAt = DateTime.UtcNow;
|
||||||
|
_reportGrades.Save(record);
|
||||||
|
RefreshItem(SelectedStudent);
|
||||||
|
ShowStudent();
|
||||||
|
StatusMessage = record.IsLocked ? "Festgeschrieben." : "Entsperrt.";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? NullIfEmpty(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||||
|
|
||||||
|
/// Ganze Note bzw. Punktzahl, optional mit Tendenz ("3+", "2-") — dieselbe Schreibweise, die
|
||||||
|
/// die Notenberechnung versteht; alles andere würde dort stillschweigend ausgelassen.
|
||||||
|
private static bool IsGradeOrEmpty(string? value)
|
||||||
|
{
|
||||||
|
var text = NullIfEmpty(value);
|
||||||
|
return text is null || int.TryParse(text.TrimEnd('+', '-').TrimEnd(), out _);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Format(double value) => value.ToString("0.00", German);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Bausteine ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
public enum AssistantGradeStatus { Open, Saved, Locked, Noted }
|
||||||
|
|
||||||
|
public partial class AssistantStudentItem(Guid studentId, string name) : ObservableObject
|
||||||
|
{
|
||||||
|
public Guid StudentId { get; } = studentId;
|
||||||
|
public string Name { get; } = name;
|
||||||
|
|
||||||
|
[ObservableProperty] private string _gradeDisplay = "–";
|
||||||
|
[ObservableProperty] private AssistantGradeStatus _status;
|
||||||
|
|
||||||
|
public string StatusLabel => Status switch
|
||||||
|
{
|
||||||
|
AssistantGradeStatus.Locked => "festgeschrieben",
|
||||||
|
AssistantGradeStatus.Saved => "gespeichert",
|
||||||
|
AssistantGradeStatus.Noted => "notiert",
|
||||||
|
_ => "offen",
|
||||||
|
};
|
||||||
|
|
||||||
|
public string StatusColorHex => Status switch
|
||||||
|
{
|
||||||
|
AssistantGradeStatus.Locked => "#2E9D57",
|
||||||
|
AssistantGradeStatus.Saved or AssistantGradeStatus.Noted => "#2E86DE",
|
||||||
|
_ => "#8A8A8A",
|
||||||
|
};
|
||||||
|
|
||||||
|
public void Update(string gradeDisplay, AssistantGradeStatus status)
|
||||||
|
{
|
||||||
|
GradeDisplay = gradeDisplay;
|
||||||
|
Status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
partial void OnStatusChanged(AssistantGradeStatus value)
|
||||||
|
{
|
||||||
|
OnPropertyChanged(nameof(StatusLabel));
|
||||||
|
OnPropertyChanged(nameof(StatusColorHex));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AssistantTile(string label, string value, string hint)
|
||||||
|
{
|
||||||
|
public string Label { get; } = label;
|
||||||
|
public string Value { get; } = value;
|
||||||
|
public string Hint { get; } = hint;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AssistantWorkCard(string title, DateOnly date, string kindLabel, string gradeDisplay,
|
||||||
|
string percentDisplay, string classAverageDisplay, bool isContext)
|
||||||
|
{
|
||||||
|
public string Title { get; } = title;
|
||||||
|
public string DateDisplay { get; } = date.ToString("dd.MM.yyyy");
|
||||||
|
public string KindLabel { get; } = kindLabel;
|
||||||
|
public string GradeDisplay { get; } = gradeDisplay;
|
||||||
|
public string PercentDisplay { get; } = percentDisplay;
|
||||||
|
public string ClassAverageDisplay { get; } = classAverageDisplay;
|
||||||
|
/// Vorhalbjahr: nur zum Vergleich gezeigt, zählt nicht in die aktuelle Note.
|
||||||
|
public bool IsContext { get; } = isContext;
|
||||||
|
public double DisplayOpacity => IsContext ? 0.45 : 1.0;
|
||||||
|
public string ContextLabel => IsContext ? "1. Halbjahr · zählt nicht" : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AssistantGradeRow(string label, DateOnly date, string value, bool isContext)
|
||||||
|
{
|
||||||
|
public string Label { get; } = label;
|
||||||
|
public string DateDisplay { get; } = date.ToString("dd.MM.yyyy");
|
||||||
|
public string Value { get; } = value;
|
||||||
|
public bool IsContext { get; } = isContext;
|
||||||
|
public double DisplayOpacity => IsContext ? 0.45 : 1.0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
|
||||||
|
public sealed record ReportGradeResult(double? Value, string? Rounded, double? Written, double? Participation, double? Other);
|
||||||
|
|
||||||
|
/// Eine Teilnote der Endjahresnote: Halbjahresnote oder Prüfungsleistung.
|
||||||
|
/// <param name="Value">Rechenwert, wenn er sich nicht aus <paramref name="Final"/> ergibt —
|
||||||
|
/// etwa eine Prüfungsleistung, die zwischen zwei Noten liegt.</param>
|
||||||
|
public sealed record YearPart(string Label, string? Final, string Hint, double Weight = 1.0, double? Value = null);
|
||||||
|
|
||||||
|
/// Prüfungsnoten der Klasse 10, soweit in diesem Fach abgelegt.
|
||||||
|
public readonly record struct YearExamGrades(string? Project, string? Oral,
|
||||||
|
string? Written = null, string? AdditionalOral = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gemeinsame Zeugnisnoten-Berechnung für Zeugnisnoten-Dialog (2.4) und Zeugnisnoten-Assistent
|
||||||
|
/// (2.7), damit beide für denselben Datensatz denselben Wert zeigen.
|
||||||
|
///
|
||||||
|
/// Halbjahre sind eigenständig und werden aus den Einzelleistungen ihres Zeitraums gewichtet.
|
||||||
|
/// Die Endjahresnote wird dagegen aus den Halbjahresnoten verrechnet (gleich gewichtet).
|
||||||
|
///
|
||||||
|
/// Klasse 10 (Bremen): In einem Prüfungsfach ergibt sich die Gesamtnote zu zwei Dritteln aus der
|
||||||
|
/// unterrichtlichen Leistung und zu einem Drittel aus der Prüfungsleistung (§ 14 Abs. 3 der
|
||||||
|
/// Verordnung über die Sekundarstufe I der Oberschule) — die Prüfung zählt also wie ein drittes
|
||||||
|
/// Halbjahr. Die Prüfungsleistung ist die Note der schriftlichen bzw. mündlichen
|
||||||
|
/// Abschlussprüfung. Kommt in einem schriftlichen Prüfungsfach eine zusätzliche mündliche
|
||||||
|
/// Prüfung hinzu, werden beide 1:1 verrechnet (§ 13 Abs. 2 PrüfV Sek. I). In einem Fach ohne
|
||||||
|
/// Abschlussprüfung zählt eine zusätzliche mündliche Prüfung selbst als Prüfungsleistung, also
|
||||||
|
/// 2:1 (§ 13 Abs. 3 PrüfV Sek. I). Die Projektprüfung zählt nach Schulpraxis als weiteres
|
||||||
|
/// Halbjahr.
|
||||||
|
///
|
||||||
|
/// Bewusst nicht umgesetzt sind die Rundungsvorgaben der Verordnungen: Noten sind
|
||||||
|
/// Leistungsbewertungen, die Entscheidung zwischen zwei Noten ist pädagogisch. Eine
|
||||||
|
/// Prüfungsleistung zwischen zwei Noten geht deshalb ungerundet in die Rechnung ein, und für die
|
||||||
|
/// Endnote gilt die von der Lehrkraft gewählte Rundung samt Möglichkeit zum Übersteuern.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ReportGradeCalculator
|
||||||
|
{
|
||||||
|
public const string ProjectExamLabel = "Projektprüfung";
|
||||||
|
public const string OralExamLabel = "Mündliche Prüfung";
|
||||||
|
public const string WrittenExamLabel = "Schriftliche Prüfung";
|
||||||
|
public const string AdditionalOralExamLabel = "Zusätzliche mündliche Prüfung";
|
||||||
|
|
||||||
|
private readonly IGradeRepository _grades;
|
||||||
|
private readonly IExamRepository _exams;
|
||||||
|
private readonly IExamResultRepository _results;
|
||||||
|
private readonly IGradingSchemeRepository _schemes;
|
||||||
|
private readonly IReportGradeRepository _reportGrades;
|
||||||
|
private readonly IReadOnlyDictionary<Guid, GroupMembership> _membershipsByStudent;
|
||||||
|
private readonly GradingService _grading;
|
||||||
|
private readonly Guid _groupId;
|
||||||
|
private readonly GroupType _groupType;
|
||||||
|
private readonly GradingSystem _gradingSystem;
|
||||||
|
private readonly string _schoolYear;
|
||||||
|
|
||||||
|
public GradingScheme Scheme { get; private set; } = new();
|
||||||
|
public List<Exam> Exams { get; private set; } = [];
|
||||||
|
public Dictionary<Guid, Dictionary<Guid, ExamResult>> ResultsByExam { get; private set; } = [];
|
||||||
|
public List<Grade> Grades { get; private set; } = [];
|
||||||
|
|
||||||
|
public string SchemeSummary =>
|
||||||
|
$"Klausuren {Scheme.ExamsPercent:0.#} % · Mitarbeit {Scheme.ParticipationPercent:0.#} % · " +
|
||||||
|
$"Sonstige {Scheme.OtherPercent:0.#} %";
|
||||||
|
|
||||||
|
public ReportGradeCalculator(IGradeRepository grades, IExamRepository exams, IExamResultRepository results,
|
||||||
|
IGradingSchemeRepository schemes, IReportGradeRepository reportGrades,
|
||||||
|
IReadOnlyDictionary<Guid, GroupMembership> membershipsByStudent, GradingService grading,
|
||||||
|
Guid groupId, GroupType groupType, GradingSystem gradingSystem, string schoolYear)
|
||||||
|
{
|
||||||
|
_grades = grades; _exams = exams; _results = results; _schemes = schemes;
|
||||||
|
_reportGrades = reportGrades; _membershipsByStudent = membershipsByStudent; _grading = grading;
|
||||||
|
_groupId = groupId; _groupType = groupType; _gradingSystem = gradingSystem; _schoolYear = schoolYear;
|
||||||
|
Reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Liest Schema, Arbeiten und Noten neu ein — vor jeder Neuberechnung einer ganzen Ansicht.
|
||||||
|
public void Reload()
|
||||||
|
{
|
||||||
|
Scheme = _schemes.GetByGroup(_groupId)
|
||||||
|
?? _schemes.GetDefaultForType(_groupType)
|
||||||
|
?? new GradingScheme { ExamsPercent = 50, ParticipationPercent = 40, OtherPercent = 10 };
|
||||||
|
Exams = _exams.GetByGroup(_groupId).OrderBy(e => e.Date).ToList();
|
||||||
|
ResultsByExam = Exams.ToDictionary(e => e.Id,
|
||||||
|
e => _results.GetByExam(e.Id).GroupBy(r => r.StudentId).ToDictionary(g => g.Key, g => g.First()));
|
||||||
|
Grades = _grades.GetByGroup(_groupId).OrderBy(g => g.Date).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public (DateOnly From, DateOnly To) Range(ParticipationPeriod period) =>
|
||||||
|
GroupMembershipService.SchoolYearPeriod(_schoolYear, period switch
|
||||||
|
{
|
||||||
|
ParticipationPeriod.H1 => SchoolYearPeriodKind.H1,
|
||||||
|
ParticipationPeriod.H2 => SchoolYearPeriodKind.H2,
|
||||||
|
_ => SchoolYearPeriodKind.FullYear,
|
||||||
|
});
|
||||||
|
|
||||||
|
public static string PeriodLabel(ParticipationPeriod period) => period switch
|
||||||
|
{
|
||||||
|
ParticipationPeriod.H1 => "1. Halbjahr",
|
||||||
|
ParticipationPeriod.H2 => "2. Halbjahr",
|
||||||
|
_ => "Gesamtes Schuljahr",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool ExamApplies(Exam exam, GroupMembership? membership)
|
||||||
|
{
|
||||||
|
if (membership is not null && !GroupMembershipService.IsActiveOn(membership, exam.Date)) return false;
|
||||||
|
return !exam.Niveau.HasValue || membership?.Niveau == exam.Niveau;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Round(double value, RoundingRule rounding) => _grading.RoundToGrade(value, _gradingSystem, rounding);
|
||||||
|
|
||||||
|
/// <param name="examGrades">Noch nicht gespeicherte Prüfungsnoten für die Jahresnote; ohne
|
||||||
|
/// Angabe gelten die am Jahres-Datensatz gespeicherten.</param>
|
||||||
|
/// <param name="asOf">Stichtag für ein Halbjahr: nur Leistungen bis einschließlich dieses
|
||||||
|
/// Tages zählen.</param>
|
||||||
|
/// <param name="runningParticipation">Vorläufige Mitarbeitsnote des laufenden, noch nicht
|
||||||
|
/// abgeschlossenen Abschnitts — zählt für ein Halbjahr wie eine weitere Abschnittsnote.</param>
|
||||||
|
public ReportGradeResult Calculate(Guid studentId, ParticipationPeriod period, RoundingRule rounding,
|
||||||
|
YearExamGrades? examGrades = null, DateOnly? asOf = null, string? runningParticipation = null)
|
||||||
|
{
|
||||||
|
if (period == ParticipationPeriod.FullYear)
|
||||||
|
{
|
||||||
|
var parts = YearParts(studentId, rounding, examGrades)
|
||||||
|
.Select(p => (Value: p.Value ?? (p.Final is null ? null : GradingService.ParseGradeValue(p.Final)), p.Weight))
|
||||||
|
.Where(p => p.Value.HasValue).ToList();
|
||||||
|
if (parts.Count == 0) return new ReportGradeResult(null, null, null, null, null);
|
||||||
|
var mean = parts.Sum(p => p.Value!.Value * p.Weight) / parts.Sum(p => p.Weight);
|
||||||
|
return new ReportGradeResult(mean, _grading.RoundToGrade(mean, _gradingSystem, rounding), null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (from, to) = Range(period);
|
||||||
|
if (asOf is { } cutoff && cutoff < to) to = cutoff;
|
||||||
|
_membershipsByStudent.TryGetValue(studentId, out var membership);
|
||||||
|
|
||||||
|
var examEntries = new List<(Exam Exam, string Grade)>();
|
||||||
|
foreach (var exam in Exams.Where(e => e.Date >= from && e.Date <= to))
|
||||||
|
{
|
||||||
|
if (!ExamApplies(exam, membership)) continue;
|
||||||
|
if (!ResultsByExam[exam.Id].TryGetValue(studentId, out var result)) continue;
|
||||||
|
if (result.Absent || result.Grade is null) continue;
|
||||||
|
examEntries.Add((exam, result.Grade));
|
||||||
|
}
|
||||||
|
var (writtenGrades, testGrades) = ExamScoringService.EffectiveGradesByKind(examEntries, _gradingSystem);
|
||||||
|
var written = writtenGrades.Select(grade => (Grade: grade, Weight: 1.0)).ToList();
|
||||||
|
|
||||||
|
var studentGrades = Grades
|
||||||
|
.Where(g => g.StudentId == studentId && g.Date >= from && g.Date <= to)
|
||||||
|
.Where(g => membership is null || GroupMembershipService.IsActiveOn(membership, g.Date))
|
||||||
|
.ToList();
|
||||||
|
var participation = studentGrades.Where(g => g.Category == GradeCategory.Participation)
|
||||||
|
.Select(g => (Grade: g.Value, g.Weight)).ToList();
|
||||||
|
if (!string.IsNullOrWhiteSpace(runningParticipation)) participation.Add((runningParticipation, 1.0));
|
||||||
|
var other = studentGrades.Where(g => g.Category != GradeCategory.Participation)
|
||||||
|
.Select(g => (Grade: g.Value, g.Weight)).ToList();
|
||||||
|
// Tests, kontrollierte Hausaufgaben u. Ä. aus der Klausurfunktion zählen als Sonstige.
|
||||||
|
other.AddRange(testGrades.Select(grade => (Grade: grade, Weight: 1.0)));
|
||||||
|
|
||||||
|
var value = _grading.CalculateReportGradeValue(written, participation, other, Scheme);
|
||||||
|
return new ReportGradeResult(value,
|
||||||
|
value is null ? null : _grading.RoundToGrade(value.Value, _gradingSystem, rounding),
|
||||||
|
written.Count > 0 ? _grading.WeightedAverage(written) : null,
|
||||||
|
participation.Count > 0 ? _grading.WeightedAverage(participation) : null,
|
||||||
|
other.Count > 0 ? _grading.WeightedAverage(other) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Die Teilnoten der Endjahresnote. Bei den Halbjahren geht eine gespeicherte Entscheidung
|
||||||
|
/// (Übersteuerung bzw. festgeschriebener Wert) der Live-Berechnung vor.
|
||||||
|
public List<YearPart> YearParts(Guid studentId, RoundingRule rounding, YearExamGrades? examGrades = null)
|
||||||
|
{
|
||||||
|
var parts = new List<YearPart>();
|
||||||
|
foreach (var half in new[] { ParticipationPeriod.H1, ParticipationPeriod.H2 })
|
||||||
|
{
|
||||||
|
var label = PeriodLabel(half);
|
||||||
|
var record = _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, label);
|
||||||
|
var overridden = NullIfEmpty(record?.OverrideValue);
|
||||||
|
if (overridden is not null)
|
||||||
|
parts.Add(new YearPart(label, overridden, record!.IsLocked ? "festgeschrieben" : "übersteuert"));
|
||||||
|
else if (record is { IsLocked: true })
|
||||||
|
parts.Add(new YearPart(label, NullIfEmpty(record.CalculatedValue), "festgeschrieben"));
|
||||||
|
else
|
||||||
|
parts.Add(new YearPart(label, Calculate(studentId, half, rounding).Rounded, "berechnet"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Die unterrichtliche Leistung zählt immer doppelt gegenüber einer Prüfung — auch wenn
|
||||||
|
// nur eine der beiden Halbjahresnoten vorliegt.
|
||||||
|
if (parts.Count(p => p.Final is not null) == 1)
|
||||||
|
parts = parts.Select(p => p.Final is null ? p : p with { Weight = 2.0 }).ToList();
|
||||||
|
|
||||||
|
var exams = examGrades ?? StoredExamGrades(studentId);
|
||||||
|
if (NullIfEmpty(exams.Project) is { } project)
|
||||||
|
parts.Add(new YearPart(ProjectExamLabel, project, "zählt wie ein Halbjahr"));
|
||||||
|
if (ExamPerformance(exams) is { } performance)
|
||||||
|
parts.Add(performance);
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Die Prüfungsleistung des Fachs, die mit einem Drittel in die Gesamtnote eingeht.
|
||||||
|
private YearPart? ExamPerformance(YearExamGrades exams)
|
||||||
|
{
|
||||||
|
var written = NullIfEmpty(exams.Written);
|
||||||
|
var oral = NullIfEmpty(exams.Oral);
|
||||||
|
var additional = NullIfEmpty(exams.AdditionalOral);
|
||||||
|
|
||||||
|
if (written is not null && additional is not null)
|
||||||
|
{
|
||||||
|
// § 13 Abs. 2 PrüfV Sek. I: 1:1. Liegt das Ergebnis zwischen zwei Noten, wird hier
|
||||||
|
// nicht gerundet — es geht so in die Endnote ein, entschieden wird dort.
|
||||||
|
var mean = _grading.WeightedAverage([(written, 1.0), (additional, 1.0)]);
|
||||||
|
var between = BetweenGrades(mean);
|
||||||
|
return new YearPart("Prüfungsleistung", mean.ToString("0.##", German),
|
||||||
|
$"schriftlich {written} · mündlich {additional}" + (between is null ? "" : $" — {between}"),
|
||||||
|
Value: mean);
|
||||||
|
}
|
||||||
|
if (written is not null) return new YearPart(WrittenExamLabel, written, "ein Drittel der Note");
|
||||||
|
if (oral is not null) return new YearPart(OralExamLabel, oral, "ein Drittel der Note");
|
||||||
|
if (additional is not null) return new YearPart(AdditionalOralExamLabel, additional, "ein Drittel der Note");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public YearExamGrades StoredExamGrades(Guid studentId)
|
||||||
|
{
|
||||||
|
var year = _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, PeriodLabel(ParticipationPeriod.FullYear));
|
||||||
|
return new YearExamGrades(year?.ProjectExamGrade, year?.OralExamGrade,
|
||||||
|
year?.WrittenExamGrade, year?.AdditionalOralExamGrade);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "zwischen 4 und 5", wenn der Wert genau auf der Grenze zweier Noten liegt — dann gibt
|
||||||
|
/// es rechnerisch keine richtige Seite, nur eine pädagogische Entscheidung.
|
||||||
|
public static string? BetweenGrades(double value)
|
||||||
|
{
|
||||||
|
var lower = Math.Floor(value);
|
||||||
|
return Math.Abs(value - lower - 0.5) < 0.0001 ? $"zwischen {lower:0} und {lower + 1:0}" : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly System.Globalization.CultureInfo German =
|
||||||
|
System.Globalization.CultureInfo.GetCultureInfo("de-DE");
|
||||||
|
|
||||||
|
private static string? NullIfEmpty(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||||
|
}
|
||||||
@@ -13,22 +13,15 @@ namespace LehrerApp.Desktop.ViewModels.Groups;
|
|||||||
|
|
||||||
public partial class ReportGradeDialogViewModel : ObservableObject
|
public partial class ReportGradeDialogViewModel : ObservableObject
|
||||||
{
|
{
|
||||||
private readonly IGradeRepository _grades;
|
|
||||||
private readonly IExamRepository _exams;
|
|
||||||
private readonly IExamResultRepository _results;
|
|
||||||
private readonly IStudentRepository _students;
|
private readonly IStudentRepository _students;
|
||||||
private readonly IGroupMembershipRepository _memberships;
|
private readonly IGroupMembershipRepository _memberships;
|
||||||
private readonly IGradingSchemeRepository _schemes;
|
|
||||||
private readonly IReportGradeRepository _reportGrades;
|
private readonly IReportGradeRepository _reportGrades;
|
||||||
|
private readonly ReportGradeCalculator _calculator;
|
||||||
private readonly IParticipationSessionRepository _participationSessions;
|
private readonly IParticipationSessionRepository _participationSessions;
|
||||||
private readonly IParticipationRepository _participation;
|
private readonly IParticipationRepository _participation;
|
||||||
private readonly AttendanceBalanceService _attendanceBalance;
|
private readonly AttendanceBalanceService _attendanceBalance;
|
||||||
private readonly GradingService _grading;
|
|
||||||
private readonly Guid _groupId;
|
private readonly Guid _groupId;
|
||||||
private readonly GroupType _groupType;
|
|
||||||
private readonly GradingSystem _gradingSystem;
|
|
||||||
private readonly string _groupLabel;
|
private readonly string _groupLabel;
|
||||||
private readonly string _schoolYear;
|
|
||||||
|
|
||||||
[ObservableProperty] private ParticipationPeriodOption _selectedPeriod;
|
[ObservableProperty] private ParticipationPeriodOption _selectedPeriod;
|
||||||
[ObservableProperty] private RoundingRule _roundingRule = RoundingRule.Commercial;
|
[ObservableProperty] private RoundingRule _roundingRule = RoundingRule.Commercial;
|
||||||
@@ -59,12 +52,13 @@ public partial class ReportGradeDialogViewModel : ObservableObject
|
|||||||
AttendanceBalanceService attendanceBalance, GradingService grading,
|
AttendanceBalanceService attendanceBalance, GradingService grading,
|
||||||
Guid groupId, GroupType groupType, GradingSystem gradingSystem, string groupLabel, string schoolYear)
|
Guid groupId, GroupType groupType, GradingSystem gradingSystem, string groupLabel, string schoolYear)
|
||||||
{
|
{
|
||||||
_grades = grades; _exams = exams; _results = results; _students = students;
|
_students = students; _memberships = memberships; _reportGrades = reportGrades;
|
||||||
_memberships = memberships; _schemes = schemes; _reportGrades = reportGrades; _grading = grading;
|
|
||||||
_participationSessions = participationSessions; _participation = participation;
|
_participationSessions = participationSessions; _participation = participation;
|
||||||
_attendanceBalance = attendanceBalance;
|
_attendanceBalance = attendanceBalance;
|
||||||
_groupId = groupId; _groupType = groupType; _gradingSystem = gradingSystem; _groupLabel = groupLabel;
|
_groupId = groupId; _groupLabel = groupLabel;
|
||||||
_schoolYear = schoolYear;
|
_calculator = new ReportGradeCalculator(grades, exams, results, schemes, reportGrades,
|
||||||
|
memberships.GetByGroup(groupId).ToDictionary(m => m.StudentId), grading,
|
||||||
|
groupId, groupType, gradingSystem, schoolYear);
|
||||||
|
|
||||||
_selectedPeriod = PeriodOptions[0];
|
_selectedPeriod = PeriodOptions[0];
|
||||||
Recompute();
|
Recompute();
|
||||||
@@ -73,31 +67,19 @@ public partial class ReportGradeDialogViewModel : ObservableObject
|
|||||||
partial void OnSelectedPeriodChanged(ParticipationPeriodOption value) => Recompute();
|
partial void OnSelectedPeriodChanged(ParticipationPeriodOption value) => Recompute();
|
||||||
partial void OnRoundingRuleChanged(RoundingRule value) => Recompute();
|
partial void OnRoundingRuleChanged(RoundingRule value) => Recompute();
|
||||||
|
|
||||||
private GradingScheme ResolveScheme() =>
|
public void Refresh() => Recompute();
|
||||||
_schemes.GetByGroup(_groupId)
|
|
||||||
?? _schemes.GetDefaultForType(_groupType)
|
|
||||||
?? new GradingScheme { ExamsPercent = 50, ParticipationPercent = 40, OtherPercent = 10 };
|
|
||||||
|
|
||||||
private void Recompute()
|
private void Recompute()
|
||||||
{
|
{
|
||||||
var scheme = ResolveScheme();
|
_calculator.Reload();
|
||||||
SchemeSummary = $"Klausuren {scheme.ExamsPercent:0.#} % · Mitarbeit {scheme.ParticipationPercent:0.#} % · " +
|
SchemeSummary = _calculator.SchemeSummary;
|
||||||
$"Sonstige {scheme.OtherPercent:0.#} %";
|
|
||||||
|
|
||||||
var period = SelectedPeriod.Period;
|
var period = SelectedPeriod.Period;
|
||||||
var periodTag = SelectedPeriod.Label;
|
var periodTag = SelectedPeriod.Label;
|
||||||
var (periodFrom, periodTo) = GroupMembershipService.SchoolYearPeriod(_schoolYear, period switch
|
var (periodFrom, periodTo) = _calculator.Range(period);
|
||||||
{
|
|
||||||
ParticipationPeriod.H1 => SchoolYearPeriodKind.H1,
|
|
||||||
ParticipationPeriod.H2 => SchoolYearPeriodKind.H2,
|
|
||||||
_ => SchoolYearPeriodKind.FullYear,
|
|
||||||
});
|
|
||||||
|
|
||||||
var students = _students.GetByGroup(_groupId);
|
var students = _students.GetByGroup(_groupId);
|
||||||
var membershipsByStudent = _memberships.GetByGroup(_groupId).ToDictionary(m => m.StudentId);
|
var membershipsByStudent = _memberships.GetByGroup(_groupId).ToDictionary(m => m.StudentId);
|
||||||
var exams = _exams.GetByGroup(_groupId).Where(e => e.Date >= periodFrom && e.Date <= periodTo).ToList();
|
|
||||||
var resultsByExam = exams.ToDictionary(e => e.Id, e => _results.GetByExam(e.Id).ToDictionary(r => r.StudentId));
|
|
||||||
var allGrades = _grades.GetByGroup(_groupId).Where(g => g.Date >= periodFrom && g.Date <= periodTo).ToList();
|
|
||||||
|
|
||||||
// Fehlquote (Nutzer-Feedback): je Schüler die Anwesenheits-Bilanz im gewählten Zeitraum,
|
// Fehlquote (Nutzer-Feedback): je Schüler die Anwesenheits-Bilanz im gewählten Zeitraum,
|
||||||
// nur aus Sitzungen dieser Gruppe (anders als StudentDetailViewModel.LoadAttendanceBalance,
|
// nur aus Sitzungen dieser Gruppe (anders als StudentDetailViewModel.LoadAttendanceBalance,
|
||||||
@@ -132,27 +114,9 @@ public partial class ReportGradeDialogViewModel : ObservableObject
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
var examGrades = new List<(string Grade, double Weight)>();
|
// Halbjahre aus den Einzelleistungen, das Schuljahr aus den Halbjahresnoten
|
||||||
foreach (var exam in exams)
|
// (plus ggf. Prüfungsnoten) — siehe ReportGradeCalculator.
|
||||||
{
|
var calculated = _calculator.Calculate(student.Id, period, RoundingRule).Rounded;
|
||||||
if (membership is not null && !GroupMembershipService.IsActiveOn(membership, exam.Date)) continue;
|
|
||||||
if (exam.Niveau.HasValue && membership?.Niveau != exam.Niveau) continue;
|
|
||||||
if (!resultsByExam[exam.Id].TryGetValue(student.Id, out var result)) continue;
|
|
||||||
if (result.Absent || result.Grade is null) continue;
|
|
||||||
examGrades.Add((result.Grade, 1.0));
|
|
||||||
}
|
|
||||||
|
|
||||||
var participationGrades = allGrades
|
|
||||||
.Where(g => g.StudentId == student.Id && g.Category == GradeCategory.Participation
|
|
||||||
&& (membership is null || GroupMembershipService.IsActiveOn(membership, g.Date)))
|
|
||||||
.Select(g => (g.Value, g.Weight)).ToList();
|
|
||||||
var otherGrades = allGrades
|
|
||||||
.Where(g => g.StudentId == student.Id && g.Category != GradeCategory.Participation
|
|
||||||
&& (membership is null || GroupMembershipService.IsActiveOn(membership, g.Date)))
|
|
||||||
.Select(g => (g.Value, g.Weight)).ToList();
|
|
||||||
|
|
||||||
var calculated = _grading.CalculateReportGrade(examGrades, participationGrades, otherGrades,
|
|
||||||
scheme, _gradingSystem, RoundingRule);
|
|
||||||
|
|
||||||
Rows.Add(ReportGradeRow.FromCalculated(student.Id, student.FullName, calculated, existing, absenceRate, Save, ToggleLock));
|
Rows.Add(ReportGradeRow.FromCalculated(student.Id, student.FullName, calculated, existing, absenceRate, Save, ToggleLock));
|
||||||
}
|
}
|
||||||
|
|||||||
Loaded 100 of 229 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user