Compare commits
42
Commits
1291b24478
...
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 | ||
|
|
4b73d2bea2 | ||
|
|
f3e23ad207 |
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
|
||||
|
||||
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`),
|
||||
and framework-free business services (`Services/`): `GradingService` (rounding, grading-key
|
||||
validation, report-grade calculation), `SchoolYearService`, `AppLogger`, `BackupService`,
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
<PackageVersion Include="Avalonia.Themes.Fluent" 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.Labs.Lottie" Version="12.0.2" />
|
||||
|
||||
<!-- MVVM & DI – .NET 10 kompatibel -->
|
||||
<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>
|
||||
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
|
||||
{
|
||||
List<GroupMembership> GetByStudent(Guid studentId);
|
||||
@@ -86,6 +94,13 @@ public interface IReportGradeRepository
|
||||
void Save(ReportGrade grade);
|
||||
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
|
||||
{
|
||||
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).
|
||||
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
|
||||
{
|
||||
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
|
||||
/// (siehe ExamDialogViewModel.Save).
|
||||
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 UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
@@ -31,6 +45,9 @@ public class ExamTask
|
||||
public string? Title { get; set; }
|
||||
public double MaxPoints { get; set; }
|
||||
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 class GradingKeyEntry
|
||||
@@ -55,7 +72,32 @@ public class ExamResult
|
||||
public double TotalPoints { get; set; }
|
||||
public string? Grade { get; set; }
|
||||
public bool Absent { get; set; }
|
||||
public ExamVariant Variant { get; set; } = ExamVariant.A;
|
||||
public string? Comment { get; set; }
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
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>
|
||||
/// 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
|
||||
/// 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>
|
||||
public int? WebUntisLessonId { get; set; }
|
||||
/// <summary>
|
||||
@@ -67,6 +68,11 @@ public class GroupMembership
|
||||
public DateOnly? JoinedAt { get; set; }
|
||||
public DateOnly? LeftAt { 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 GroupType { Class, Course }
|
||||
|
||||
@@ -258,6 +258,42 @@ public class ReportGrade
|
||||
public string? OverrideValue { get; set; }
|
||||
public string? OverrideReason { 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -52,9 +52,10 @@ public sealed record StudentReferenceSummary(
|
||||
int Grades,
|
||||
int ReportGrades,
|
||||
int ParticipationEntries,
|
||||
int DocumentationEntries)
|
||||
int DocumentationEntries,
|
||||
int StudentGroupPlans = 0)
|
||||
{
|
||||
public int Total => Memberships + ExamResults + Grades + ReportGrades
|
||||
+ ParticipationEntries + DocumentationEntries;
|
||||
+ ParticipationEntries + DocumentationEntries + StudentGroupPlans;
|
||||
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>
|
||||
public class UntisCacheFetchState
|
||||
{
|
||||
public int AbsenceReportVersion { get; set; }
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
public string ClassName { get; set; } = "";
|
||||
public UntisCacheKind Kind { get; set; }
|
||||
|
||||
@@ -3,7 +3,14 @@ namespace LehrerApp.Core.Models;
|
||||
public class Documentation : IHasAttachments
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
/// <summary>Hauptperson des Eintrags (bei Gruppeneinträgen <see cref="Guid.Empty"/>).</summary>
|
||||
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; }
|
||||
/// <summary>Unterrichtssitzung, in der die Beobachtung entstanden ist.</summary>
|
||||
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).
|
||||
public bool IsDeleted { 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
|
||||
{
|
||||
|
||||
@@ -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
|
||||
/// bedeuten unabhängig von der Klasse mehr Erstellungsaufwand vorher und mehr Korrekturaufwand
|
||||
/// danach. Da eine LiteDB-Datei genau einem Nutzer gehört (siehe CLAUDE.md), sind "alle
|
||||
/// Klausuren in der Datenbank" bereits gleichbedeutend mit "meine Klausuren".
|
||||
/// 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>
|
||||
public static class ExamWeekLoadService
|
||||
{
|
||||
@@ -24,7 +25,8 @@ public static class ExamWeekLoadService
|
||||
public static int CountInSameWeek(IEnumerable<Exam> allExams, DateOnly date, Guid? excludeExamId = null)
|
||||
{
|
||||
var (year, week) = IsoWeek(date);
|
||||
return allExams.Count(e => e.Id != excludeExamId && IsoWeek(e.Date) == (year, week));
|
||||
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
|
||||
@@ -32,6 +34,7 @@ public static class ExamWeekLoadService
|
||||
/// vorausschauenden Überblick (z.B. Dashboard), nicht für die Einzelprüfung beim Anlegen.
|
||||
public static List<ExamWeekLoad> FindOverloadedWeeks(IEnumerable<Exam> exams) =>
|
||||
exams
|
||||
.Where(e => e.Kind.CountsAsWritten())
|
||||
.GroupBy(e => IsoWeek(e.Date))
|
||||
.Where(g => g.Count() >= WarningThreshold)
|
||||
.Select(g => new ExamWeekLoad(g.Key.Year, g.Key.Week, WeekStart(g.Key.Year, g.Key.Week), g.Count()))
|
||||
|
||||
@@ -87,7 +87,7 @@ public class GradingService
|
||||
/// Wandelt eine Notenangabe mit optionaler Tendenz ("3+", "2-") in einen rechnerischen
|
||||
/// Notenwert um. Tendenzen verschieben um ein Drittel in Richtung der besseren Note
|
||||
/// (z.B. "3+" → 2,67, "2-" → 2,33) — der in deutschen Notensystemen übliche Drittelabstand.
|
||||
private static double? ParseGradeValue(string grade)
|
||||
public static double? ParseGradeValue(string grade)
|
||||
{
|
||||
var trimmed = grade.Trim();
|
||||
if (trimmed.Length == 0) return null;
|
||||
@@ -132,6 +132,18 @@ public class GradingService
|
||||
List<(string Grade, double Weight)> participationGrades,
|
||||
List<(string Grade, double Weight)> otherGrades,
|
||||
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)>();
|
||||
if (examGrades.Count > 0) buckets.Add((WeightedAverage(examGrades), scheme.ExamsPercent));
|
||||
@@ -141,8 +153,7 @@ public class GradingService
|
||||
var totalPercent = buckets.Sum(b => b.Percent);
|
||||
if (buckets.Count == 0 || totalPercent <= 0) return null;
|
||||
|
||||
var weighted = buckets.Sum(b => b.Avg * b.Percent) / totalPercent;
|
||||
return RoundToGrade(weighted, system, rounding);
|
||||
return buckets.Sum(b => b.Avg * b.Percent) / totalPercent;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,11 @@ public enum SchoolYearPeriodKind { FullYear, H1, H2 }
|
||||
/// </summary>
|
||||
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)
|
||||
{
|
||||
if (membership.JoinedAt is { } joinedAt && date < joinedAt) return false;
|
||||
|
||||
@@ -80,6 +80,7 @@ public sealed class GroupRolloverService(
|
||||
JoinedAt = targetStart,
|
||||
LeftAt = null,
|
||||
Niveau = membership.Niveau,
|
||||
IsSupportStudent = membership.IsSupportStudent,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,8 @@ public class PersonalDataExportService(
|
||||
IExamResultRepository examResults,
|
||||
IParticipationRepository participation,
|
||||
IDocumentationRepository documentation,
|
||||
ISeatingPlanRepository seatingPlans)
|
||||
ISeatingPlanRepository seatingPlans,
|
||||
IStudentGroupPlanRepository? studentGroupPlans = null)
|
||||
{
|
||||
public string ExportAsJson(Guid studentId)
|
||||
{
|
||||
@@ -56,6 +57,16 @@ public class PersonalDataExportService(
|
||||
Platz = a.Column + 1,
|
||||
}))
|
||||
.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
|
||||
|
||||
@@ -61,6 +61,15 @@ public sealed class ChangeHookMatrixTests
|
||||
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 =>
|
||||
{
|
||||
var repo = new UnitRepository(db);
|
||||
|
||||
@@ -77,4 +77,26 @@ public sealed class ChangeHookTests
|
||||
Assert.Equal("Save", call.Operation);
|
||||
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 context = new LiteDbContext(temp.Path);
|
||||
|
||||
Assert.Equal(6, context.SchemaVersion);
|
||||
Assert.Equal(7, context.SchemaVersion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -132,7 +132,30 @@ public sealed class LiteDbContextTests
|
||||
|
||||
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]
|
||||
|
||||
@@ -8,6 +8,72 @@ public sealed class RepositoryTests
|
||||
{
|
||||
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 ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
@@ -1338,4 +1404,39 @@ public sealed class RepositoryTests
|
||||
|
||||
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<LearningGroup> Groups => _db.GetCollection<LearningGroup>("groups");
|
||||
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<Exam> Exams => _db.GetCollection<Exam>("exams");
|
||||
public ILiteCollection<ExamResult> ExamResults => _db.GetCollection<ExamResult>("exam_results");
|
||||
public ILiteCollection<Grade> Grades => _db.GetCollection<Grade>("grades");
|
||||
public ILiteCollection<GradingScheme> GradingSchemes => _db.GetCollection<GradingScheme>("grading_schemes");
|
||||
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<Unit> Units => _db.GetCollection<Unit>("units");
|
||||
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<UntisStudentRosterCacheEntry> UntisStudentRosterCache => _db.GetCollection<UntisStudentRosterCacheEntry>("untis_student_roster_cache");
|
||||
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 void Checkpoint() => _db.Checkpoint();
|
||||
@@ -112,6 +115,9 @@ public class LiteDbContext : IDisposable
|
||||
foreach (var reportGrade in ReportGrades.Find(g => g.GroupId == id).ToList())
|
||||
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())
|
||||
GradingSchemes.Delete(scheme.Id);
|
||||
|
||||
@@ -140,6 +146,8 @@ public class LiteDbContext : IDisposable
|
||||
|
||||
foreach (var plan in SeatingPlans.Find(p => p.GroupId == id).ToList())
|
||||
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,
|
||||
// werden aber von der nicht mehr existierenden Lerngruppe entkoppelt.
|
||||
@@ -273,9 +281,31 @@ public class LiteDbContext : IDisposable
|
||||
MigrateCompetencyReferences();
|
||||
version = 6;
|
||||
}
|
||||
if (version < 7)
|
||||
{
|
||||
MigrateDashboardWarningSnoozeIds();
|
||||
version = 7;
|
||||
}
|
||||
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()
|
||||
{
|
||||
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.IsActive);
|
||||
SeatingPlans.EnsureIndex(x => x.GroupId);
|
||||
StudentGroupPlans.EnsureIndex(x => x.GroupId);
|
||||
Memberships.EnsureIndex(x => x.StudentId);
|
||||
Memberships.EnsureIndex(x => x.GroupId);
|
||||
Memberships.EnsureIndex("ux_student_group",
|
||||
@@ -654,6 +685,8 @@ public class LiteDbContext : IDisposable
|
||||
ReportGrades.EnsureIndex(x => x.StudentId);
|
||||
ReportGrades.EnsureIndex("ux_student_group_period",
|
||||
BsonExpression.Create("STRING($.StudentId) + ':' + STRING($.GroupId) + ':' + $.Period"), unique: true);
|
||||
InterimGrades.EnsureIndex(x => x.GroupId);
|
||||
InterimGrades.EnsureIndex(x => x.StudentId);
|
||||
GradingKeyTemplates.EnsureIndex(x => x.GradingSystem);
|
||||
Units.EnsureIndex(x => x.GroupId);
|
||||
Lessons.EnsureIndex(x => x.UnitId);
|
||||
@@ -694,6 +727,8 @@ public class LiteDbContext : IDisposable
|
||||
UntisStudentRosterCache.EnsureIndex(x => x.ClassName);
|
||||
UntisCacheFetchStates.EnsureIndex("ux_class_kind",
|
||||
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();
|
||||
|
||||
@@ -32,9 +32,12 @@ public class StudentRepository(LiteDbContext db) : IStudentRepository
|
||||
db.Memberships.Count(m => m.StudentId == studentId),
|
||||
db.ExamResults.Count(r => r.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.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)
|
||||
{
|
||||
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 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
|
||||
{
|
||||
// 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) =>
|
||||
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) =>
|
||||
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();
|
||||
public List<Documentation> GetAll() =>
|
||||
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 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 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
|
||||
{
|
||||
[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]
|
||||
public void Monatskalender_KodiertFehlzeitenUndBlendetHausaufgabenStandardmaessigAus()
|
||||
{
|
||||
@@ -32,7 +64,7 @@ public sealed class ClassTeacherViewModelsTests
|
||||
|
||||
Assert.Equal(0, days.Count % 5);
|
||||
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "V");
|
||||
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "U");
|
||||
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "T");
|
||||
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "!");
|
||||
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.False(days[0].HasSignal);
|
||||
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.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
|
||||
}
|
||||
|
||||
@@ -87,7 +119,7 @@ public sealed class ClassTeacherViewModelsTests
|
||||
var days = ClassTeacherOverviewViewModel.BuildCompactMonthDays(month, absences, [], month,
|
||||
"Ada Müller");
|
||||
|
||||
Assert.Equal("U", days[2].SignalCode);
|
||||
Assert.Equal("T", days[2].SignalCode);
|
||||
Assert.False(days[3].HasSignal);
|
||||
}
|
||||
|
||||
@@ -107,7 +139,7 @@ public sealed class ClassTeacherViewModelsTests
|
||||
|
||||
Assert.True(drawing.ContentHeight > 0);
|
||||
Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "Ada Müller");
|
||||
Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "U");
|
||||
Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "T");
|
||||
Assert.DoesNotContain(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "E");
|
||||
}
|
||||
|
||||
@@ -367,6 +399,24 @@ public sealed class ClassTeacherViewModelsTests
|
||||
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]
|
||||
public void GroupByStudentAndDay_TrenntGleichenNamenAnUnterschiedlichenTagen()
|
||||
{
|
||||
@@ -509,11 +559,14 @@ public sealed class ClassTeacherViewModelsTests
|
||||
termStart: new DateOnly(2026, 8, 1)));
|
||||
|
||||
Assert.True(row.HasYearSummary);
|
||||
Assert.Equal(2, row.YearAbsenceDayCount);
|
||||
Assert.Equal(1, row.YearAbsenceDayCount);
|
||||
Assert.Equal(1, row.YearUnexcusedDayCount);
|
||||
Assert.Equal(10, row.YearAbsenceRatePercent);
|
||||
Assert.Contains("10 %", row.YearSummaryLabel);
|
||||
Assert.Contains("2 von 20", row.YearSummaryTooltip);
|
||||
Assert.Equal(2, row.YearAbsencePeriodCount);
|
||||
Assert.Equal(2, row.YearExcusedPeriodCount);
|
||||
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("1 unentschuldigt", row.YearSummaryTooltip);
|
||||
}
|
||||
@@ -577,24 +630,30 @@ public sealed class ClassTeacherViewModelsTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RosterBuild_UnentschuldigtUndVerspaetetZaehltAlsUnentschuldigtNichtAlsVerspaetung()
|
||||
public void RosterBuild_UnentschuldigteFehlstundeZaehltNichtAlsGanzerFehltag()
|
||||
{
|
||||
// Wer unentschuldigt UND verspätet ist, bleibt der schwerwiegendere Fall (dieselbe
|
||||
// Rangfolge wie AttentionRank/StatusKind/BuildTrend: Unentschuldigt vor Verspätet) — zählt
|
||||
// deshalb weiter voll in die Quote statt in YearLateDayCount zu verschwinden.
|
||||
// Kernfall: Eine Schülerin fehlt aus Protest eine Unterrichtsstunde. Das bleibt
|
||||
// unentschuldigt und score-relevant, darf im Zeugnis-/Jahresstand aber nicht als ganzer
|
||||
// unentschuldigter Fehltag erscheinen.
|
||||
var students = new[] { Student(1001, "Ada Müller") };
|
||||
var yearAbsences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10), "Müller Ada", 1001, 0, 60,
|
||||
["Deu"], [1], ["nicht entsch."], ["Verspätung"], null, null, false),
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10), "Müller Ada", 1001, 1, 45,
|
||||
["Deu"], [1], ["nicht entsch."], ["Absent"], "Aus Protest gegangen", null, false),
|
||||
};
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1)));
|
||||
|
||||
Assert.Equal(1, row.YearAbsenceDayCount);
|
||||
Assert.Equal(1, row.YearUnexcusedDayCount);
|
||||
Assert.Equal(0, row.YearAbsenceDayCount);
|
||||
Assert.Equal(0, row.YearUnexcusedDayCount);
|
||||
Assert.Equal(1, row.YearAbsencePeriodCount);
|
||||
Assert.Equal(1, row.YearUnexcusedPeriodCount);
|
||||
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]
|
||||
@@ -754,7 +813,8 @@ public sealed class ClassTeacherViewModelsTests
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [], new DateOnly(2026, 8, 26),
|
||||
yearAbsences, schoolDaysElapsed: 10));
|
||||
|
||||
Assert.Equal(1, row.YearAbsenceDayCount);
|
||||
Assert.Equal(0, row.YearAbsenceDayCount);
|
||||
Assert.Equal(2, row.YearAbsencePeriodCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -963,9 +1023,9 @@ public sealed class ClassTeacherViewModelsTests
|
||||
var absences = new[]
|
||||
{
|
||||
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,
|
||||
["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" };
|
||||
|
||||
@@ -978,6 +1038,26 @@ public sealed class ClassTeacherViewModelsTests
|
||||
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) ──────────────────
|
||||
|
||||
[Fact]
|
||||
@@ -1230,6 +1310,18 @@ public sealed class ClassTeacherViewModelsTests
|
||||
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 ─────────
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.ViewModels;
|
||||
@@ -83,6 +84,11 @@ public sealed class DashboardViewModelTests
|
||||
private static IEnumerable<AttentionItem> Items(DashboardViewModel vm, AttentionKind kind) =>
|
||||
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
|
||||
/// formatierte Anzeigetext) — das genaue Datum steckt im mitgegebenen Action-Parameter
|
||||
/// (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,
|
||||
FakeReportGrades? reportGrades = null, FakeMemberships? memberships = null,
|
||||
FakeWorkTasks? tasks = null, FakeStudents? students = null, FakeDocumentation? documentation = null,
|
||||
FakeVorgangRepository? vorgaenge = null, FakeDashboardWarningSnoozeRepository? warningSnoozes = null,
|
||||
DashboardSettingsService? dashboardSettings = null, FakeSchoolHolidays? schoolHolidays = null,
|
||||
FakeLessons? lessons = null, FakeSubstitutionEntries? substitutions = null,
|
||||
FakeSessions? sessions = null, FakeEntries? entries = null,
|
||||
@@ -157,6 +164,7 @@ public sealed class DashboardViewModelTests
|
||||
reportGrades ?? new FakeReportGrades(), memberships ?? new FakeMemberships([]),
|
||||
tasks ?? new FakeWorkTasks(), sessions ?? new FakeSessions([]), entries ?? new FakeEntries(),
|
||||
students ?? new FakeStudents([]), documentation ?? new FakeDocumentation(),
|
||||
vorgaenge ?? new FakeVorgangRepository(), warningSnoozes ?? new FakeDashboardWarningSnoozeRepository(),
|
||||
slots ?? new FakeTimetableSlots(), periodSchedule ?? NewPeriodSchedule(),
|
||||
new AttendanceBalanceService(), new SchoolYearService(), dashboardSettings ?? NewDashboardSettings(),
|
||||
schoolHolidays ?? new FakeSchoolHolidays(), new PublicHolidayService(), NewCalendarSettings(),
|
||||
@@ -805,10 +813,365 @@ public sealed class DashboardViewModelTests
|
||||
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||
Assert.Equal(student.FullName, item.Title);
|
||||
Assert.Equal("30 %", item.TrailingText);
|
||||
Assert.True(item.IsAttendanceWarning);
|
||||
Assert.True(item.IsCrossClassWarning);
|
||||
Assert.Equal(AttentionKind.Attendance, vm.Attention.First().Kind);
|
||||
}
|
||||
|
||||
/// Fehlzeiten-Warnungen landen seit der Verknüpfung mit dem schülerbezogenen "Vorgänge"-Tab auf
|
||||
/// OnNavigateToStudentCase (mit dem passenden Tag "Absentismus") statt auf OnNavigateToStudent.
|
||||
[Fact]
|
||||
public void AttendanceWarnings_NavigiertUeberOnNavigateToStudentCaseMitAbsentismusTag()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||
sessions.Save(session);
|
||||
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
|
||||
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||
}
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||
|
||||
Guid? navigatedStudentId = null; string? navigatedTag = null; string? navigatedTitle = null;
|
||||
vm.OnNavigateToStudentCase = (id, tag, title) => { navigatedStudentId = id; navigatedTag = tag; navigatedTitle = title; };
|
||||
vm.OnNavigateToStudent = _ => throw new InvalidOperationException("sollte nicht mehr aufgerufen werden");
|
||||
|
||||
Assert.Single(Items(vm, AttentionKind.Attendance)).Navigate!.Invoke();
|
||||
|
||||
Assert.Equal(student.Id, navigatedStudentId);
|
||||
Assert.Equal("Absentismus", navigatedTag);
|
||||
Assert.Equal("Fehlzeiten", navigatedTitle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MissingHomeworkWarnings_UnterSchwellenwertKeineWarnung()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
|
||||
// Nur 2 offene Hausaufgaben — Schwelle liegt bei 3.
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||
sessions.Save(session);
|
||||
entries.Add(new ParticipationEntry
|
||||
{ SessionId = session.Id, StudentId = student.Id, Homework = HomeworkStatus.MissingOpen });
|
||||
}
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||
|
||||
Assert.Empty(Items(vm, AttentionKind.MissingHomework));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MissingHomeworkWarnings_MeldetAbSchwellenwertUndZaehltPartiallyCompletedAlsOffen()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
|
||||
// 3 offene/überfällige Hausaufgaben (davon eine PartiallyCompleted, zählt laut
|
||||
// HomeworkDisplay.CountsAsMissing ebenfalls als offen) — erreicht die Schwelle von 3.
|
||||
var statuses = new[] { HomeworkStatus.MissingOpen, HomeworkStatus.MissingOverdue, HomeworkStatus.PartiallyCompleted };
|
||||
for (var i = 0; i < statuses.Length; i++)
|
||||
{
|
||||
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||
sessions.Save(session);
|
||||
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Homework = statuses[i] });
|
||||
}
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||
|
||||
var item = Assert.Single(Items(vm, AttentionKind.MissingHomework));
|
||||
Assert.Equal(student.FullName, item.Title);
|
||||
Assert.Equal("3 offen", item.TrailingText);
|
||||
|
||||
Guid? navigatedStudentId = null; string? navigatedTag = null;
|
||||
vm.OnNavigateToStudentCase = (id, tag, _) => { navigatedStudentId = id; navigatedTag = tag; };
|
||||
item.Navigate!.Invoke();
|
||||
Assert.Equal(student.Id, navigatedStudentId);
|
||||
Assert.Equal("Hausaufgaben", navigatedTag);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LatenessWarnings_UnterSchwellenwertKeineWarnung()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
|
||||
// Nur 7 Verspätungen — Schwelle liegt bei 8.
|
||||
for (var i = 0; i < 7; i++)
|
||||
{
|
||||
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||
sessions.Save(session);
|
||||
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = AttendanceStatus.Late });
|
||||
}
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||
|
||||
Assert.Empty(Items(vm, AttentionKind.Lateness));
|
||||
}
|
||||
|
||||
/// Regressionsschutz: Late/SignificantlyLate zählen bewusst NICHT in die Fehlzeitenquote hinein
|
||||
/// (AttendanceBalanceService behandelt sie als Present) — auch wenn ein Schüler die neue
|
||||
/// Verspätungs-Schwelle reißt, darf die bestehende Fehlzeiten-Warnung dadurch nicht auftauchen.
|
||||
[Fact]
|
||||
public void LatenessWarnings_MeldetAbSchwellenwertUndZaehltNichtAlsFehlzeit()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
|
||||
// 5x Late, 3x SignificantlyLate — zusammen 8, erreicht die Schwelle.
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||
sessions.Save(session);
|
||||
var status = i < 5 ? AttendanceStatus.Late : AttendanceStatus.SignificantlyLate;
|
||||
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||
}
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||
|
||||
var item = Assert.Single(Items(vm, AttentionKind.Lateness));
|
||||
Assert.Equal(student.FullName, item.Title);
|
||||
Assert.Equal("8× verspätet", item.TrailingText);
|
||||
Assert.Empty(Items(vm, AttentionKind.Attendance));
|
||||
}
|
||||
|
||||
// ── Entschärfen (Nutzer-Feedback: "erledigt" wirkt grau/hinten, ohne dauerhaft stumm zu bleiben) ──
|
||||
|
||||
private static (Student Handled, Student Active) BuildTwoOverThresholdStudents(
|
||||
LearningGroup group, DateOnly today, FakeSessions sessions, FakeEntries entries)
|
||||
{
|
||||
var handled = new Student { FirstName = "Anna", LastName = "Bearbeitet" };
|
||||
var active = new Student { FirstName = "Ben", LastName = "Unbearbeitet" };
|
||||
foreach (var student in new[] { handled, active })
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||
sessions.Save(session);
|
||||
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
|
||||
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||
}
|
||||
return (handled, active);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AttendanceWarnings_MitKuerzlichBearbeitetemVorgang_WandertInZurueckgestelltGruppe()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||
|
||||
var vorgaenge = new FakeVorgangRepository();
|
||||
vorgaenge.Add(new Vorgang
|
||||
{
|
||||
Title = "Fehlzeiten", StudentIds = [handled.Id], Tags = ["Absentismus"],
|
||||
Status = VorgangStatus.Open, UpdatedAt = DateTime.UtcNow.AddDays(-2),
|
||||
});
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||
vorgaenge: vorgaenge);
|
||||
|
||||
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||
Assert.False(item.IsDefused);
|
||||
Assert.Equal(active.FullName, item.Title);
|
||||
var deferred = Assert.Single(DeferredItems(vm));
|
||||
Assert.True(deferred.IsDefused);
|
||||
Assert.Equal(handled.FullName, deferred.Title);
|
||||
Assert.Equal("Fehlzeiten · Vorgang in Bearbeitung", deferred.Subtitle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AttendanceWarnings_VorgangAelterAlsFrist_BleibtScharf()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
var (handled, _) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||
|
||||
var vorgaenge = new FakeVorgangRepository();
|
||||
// 20 Tage her — jenseits der 14-Tage-Frist (VorgangDefusalGraceDays).
|
||||
vorgaenge.Add(new Vorgang
|
||||
{
|
||||
Title = "Fehlzeiten", StudentIds = [handled.Id], Tags = ["Absentismus"],
|
||||
Status = VorgangStatus.Open, UpdatedAt = DateTime.UtcNow.AddDays(-20),
|
||||
});
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([handled]), sessions: sessions, entries: entries, vorgaenge: vorgaenge);
|
||||
|
||||
Assert.False(Assert.Single(Items(vm, AttentionKind.Attendance)).IsDefused);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AttendanceWarnings_AktiveZurueckstellungIstEntschaerft_AbgelaufeneNichtMehr()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||
|
||||
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||
snoozes.Save(new DashboardWarningSnooze { StudentId = handled.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
|
||||
snoozes.Save(new DashboardWarningSnooze { StudentId = active.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(-1) });
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||
warningSnoozes: snoozes);
|
||||
|
||||
Assert.Equal(active.FullName, Assert.Single(Items(vm, AttentionKind.Attendance)).Title);
|
||||
var deferred = Assert.Single(DeferredItems(vm));
|
||||
Assert.Equal(handled.FullName, deferred.Title);
|
||||
Assert.Equal($"Fehlzeiten · zurückgestellt bis {today.AddDays(7):dd.MM.}", deferred.Subtitle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZurueckgestelltGruppe_StehtEingeklapptAmEndeUndZaehltNichtMit()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||
snoozes.Save(new DashboardWarningSnooze { StudentId = handled.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||
warningSnoozes: snoozes);
|
||||
|
||||
var last = vm.Attention.Last();
|
||||
Assert.True(last.IsDeferred);
|
||||
Assert.Null(last.Kind);
|
||||
Assert.False(last.IsExpanded);
|
||||
Assert.Equal(1, vm.AttentionCount);
|
||||
Assert.True(vm.HasOpenAttention);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZurueckgestelltGruppe_AufklappzustandUeberlebtNeuaufbauUndFilterBlendetAus()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
|
||||
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||
snoozes.Save(new DashboardWarningSnooze { StudentId = handled.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
|
||||
snoozes.Save(new DashboardWarningSnooze { StudentId = active.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||
warningSnoozes: snoozes);
|
||||
|
||||
// Nur noch zurückgestellte Warnungen: kein offener Punkt, Kachel bleibt aber erreichbar.
|
||||
Assert.Equal(0, vm.AttentionCount);
|
||||
Assert.False(vm.HasOpenAttention);
|
||||
Assert.False(vm.AttentionCard.IsEmpty);
|
||||
|
||||
vm.Attention.Single(g => g.IsDeferred).ToggleExpandedCommand.Execute(null);
|
||||
var filter = vm.AttentionFilters.Single(f => f.Kind == AttentionKind.Attendance);
|
||||
filter.IsActive = false;
|
||||
Assert.DoesNotContain(vm.Attention, g => g.IsDeferred);
|
||||
filter.IsActive = true;
|
||||
|
||||
Assert.True(vm.Attention.Single(g => g.IsDeferred).IsExpanded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SnoozeAction_FragtNachUndEntschaerftDieWarnungSofort()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||
sessions.Save(session);
|
||||
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
|
||||
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||
}
|
||||
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([student]), sessions: sessions, entries: entries, warningSnoozes: snoozes);
|
||||
|
||||
string? shownMessage = null;
|
||||
vm.OnPickSnoozeDuration = message => { shownMessage = message; return Task.FromResult<int?>(14); };
|
||||
|
||||
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||
Assert.False(item.IsDefused);
|
||||
var snoozeAction = Assert.Single(item.Actions, a => a.Label == "Zurückstellen");
|
||||
await ((IAsyncRelayCommand)snoozeAction.Command).ExecuteAsync(null);
|
||||
|
||||
Assert.Contains(student.FullName, shownMessage);
|
||||
var saved = Assert.Single(snoozes.GetAll());
|
||||
Assert.Equal(student.Id, saved.StudentId);
|
||||
Assert.Equal("Absentismus", saved.WarningTag);
|
||||
Assert.Equal(today.AddDays(14), saved.SnoozedUntil);
|
||||
Assert.Empty(Items(vm, AttentionKind.Attendance));
|
||||
Assert.True(Assert.Single(DeferredItems(vm)).IsDefused);
|
||||
Assert.Equal(0, vm.AttentionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SnoozeAction_AbbruchSpeichertNichts()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||
var sessions = new FakeSessions([]);
|
||||
var entries = new FakeEntries();
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
|
||||
sessions.Save(session);
|
||||
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
|
||||
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
|
||||
}
|
||||
var snoozes = new FakeDashboardWarningSnoozeRepository();
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([student]), sessions: sessions, entries: entries, warningSnoozes: snoozes);
|
||||
vm.OnPickSnoozeDuration = _ => Task.FromResult<int?>(null);
|
||||
|
||||
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||
var snoozeAction = Assert.Single(item.Actions, a => a.Label == "Zurückstellen");
|
||||
await ((IAsyncRelayCommand)snoozeAction.Command).ExecuteAsync(null);
|
||||
|
||||
Assert.Empty(snoozes.GetAll());
|
||||
Assert.False(Assert.Single(Items(vm, AttentionKind.Attendance)).IsDefused);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddTask_SpeichertErgebnisUndAktualisiertOffeneAufgaben()
|
||||
{
|
||||
|
||||
@@ -308,4 +308,89 @@ public sealed class DocumentationDialogViewModelTests
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
[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.Services;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
@@ -62,4 +63,166 @@ public sealed class ExamGradingDialogViewModelTests
|
||||
|
||||
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 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
|
||||
{
|
||||
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 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
|
||||
{
|
||||
private readonly List<Grade> _all = [];
|
||||
@@ -320,15 +344,41 @@ public class FakeDocumentation : IDocumentationRepository
|
||||
private readonly List<Documentation> _all = [];
|
||||
public void Add(Documentation d) => _all.Add(d);
|
||||
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) =>
|
||||
_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 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 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
|
||||
{
|
||||
private readonly Dictionary<string, byte[]> _blobs = [];
|
||||
@@ -631,6 +681,17 @@ public class FakeTimeEntries : ITimeEntryRepository
|
||||
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
|
||||
{
|
||||
private readonly List<ReportGrade> _all = [];
|
||||
|
||||
@@ -22,7 +22,7 @@ public sealed class GroupDetailViewModelTests
|
||||
new FakeDocumentation(), tasks, groups, new AttendanceBalanceService(), new GradingService(), new SchoolYearService()),
|
||||
new ParticipationTabViewModel(new FakeSessions([]), new FakeEntries(), new FakeAspects(),
|
||||
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 FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), new FakeSessions([])),
|
||||
new CompetencyOverviewTabViewModel(new FakeUnits(), exams, new FakeResults(),
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class HomeworkOverdueServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public void Advance_Nach14Kalendertagen_NurOffeneNachreichungen()
|
||||
{
|
||||
var today = new DateOnly(2026, 9, 25);
|
||||
var group = new LearningGroup { IsActive = true };
|
||||
var archived = new LearningGroup { IsActive = false };
|
||||
var dueSession = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-14) };
|
||||
var recentSession = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-13) };
|
||||
var archivedSession = new ParticipationSession { GroupId = archived.Id, Date = today.AddDays(-30) };
|
||||
var open = new ParticipationEntry { SessionId = dueSession.Id, Homework = HomeworkStatus.MissingOpen };
|
||||
var legacy = new ParticipationEntry { SessionId = dueSession.Id, HomeworkMissing = true };
|
||||
var submitted = new ParticipationEntry { SessionId = dueSession.Id, Homework = HomeworkStatus.SubmittedLate };
|
||||
var partial = new ParticipationEntry { SessionId = dueSession.Id, Homework = HomeworkStatus.PartiallyCompleted };
|
||||
var recent = new ParticipationEntry { SessionId = recentSession.Id, Homework = HomeworkStatus.MissingOpen };
|
||||
var oldArchived = new ParticipationEntry { SessionId = archivedSession.Id, Homework = HomeworkStatus.MissingOpen };
|
||||
var entries = new FakeEntries();
|
||||
foreach (var entry in new[] { open, legacy, submitted, partial, recent, oldArchived }) entries.Add(entry);
|
||||
var service = new HomeworkOverdueService(new FakeGroups([group, archived]),
|
||||
new FakeSessions([dueSession, recentSession, archivedSession]), entries);
|
||||
|
||||
Assert.Equal(2, service.Advance(today));
|
||||
Assert.Equal(HomeworkStatus.MissingOverdue, open.Homework);
|
||||
Assert.Equal(HomeworkStatus.MissingOverdue, legacy.Homework);
|
||||
Assert.True(open.HomeworkMissing);
|
||||
Assert.True(legacy.HomeworkMissing);
|
||||
Assert.Equal(HomeworkStatus.SubmittedLate, submitted.Homework);
|
||||
Assert.Equal(HomeworkStatus.PartiallyCompleted, partial.Homework);
|
||||
Assert.Equal(HomeworkStatus.MissingOpen, recent.Homework);
|
||||
Assert.Equal(HomeworkStatus.MissingOpen, oldArchived.Homework);
|
||||
Assert.Equal(0, service.Advance(today));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="PdfPig" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
|
||||
@@ -8,6 +8,43 @@ namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
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()
|
||||
{
|
||||
var tempPath = System.IO.Path.Combine(
|
||||
|
||||
@@ -31,8 +31,14 @@ public sealed class PersonalDataExportServiceTests
|
||||
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,
|
||||
documentation, seatingPlans);
|
||||
documentation, seatingPlans, groupPlans);
|
||||
|
||||
var json = service.ExportAsJson(studentId);
|
||||
|
||||
@@ -41,6 +47,7 @@ public sealed class PersonalDataExportServiceTests
|
||||
Assert.Contains("\"Value\": \"2\"", json);
|
||||
Assert.Contains("\"Sitzplan\": \"Standard\"", json);
|
||||
Assert.Contains("\"Reihe\": 2", json);
|
||||
Assert.Contains("Projektwoche", json);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -53,4 +60,23 @@ public sealed class PersonalDataExportServiceTests
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
[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]
|
||||
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;
|
||||
|
||||
public sealed class SettingsViewModelTests
|
||||
public sealed partial class SettingsViewModelTests
|
||||
{
|
||||
private static SettingsViewModel BuildViewModel(FakeSchoolHolidays? holidays = null,
|
||||
FakeSupervisionDuties? supervisionDuties = null,
|
||||
@@ -19,7 +19,7 @@ public sealed class SettingsViewModelTests
|
||||
FakeCompetencyCatalogVersions? competencyVersions = null,
|
||||
EventQueue? eventQueue = null, SyncKeyStatus? syncKeyStatus = 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,
|
||||
// das Verzeichnis muss über die Lebensdauer des ViewModels bestehen bleiben.
|
||||
@@ -37,7 +37,7 @@ public sealed class SettingsViewModelTests
|
||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||
holidays ?? new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath),
|
||||
new PeriodScheduleService(tempPath), supervisionDuties ?? new FakeSupervisionDuties(),
|
||||
new TemplateStore(tempPath), 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.BuildMcpClientRegistrationService(),
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class TeachingModeOutstandingHomeworkViewModelTests
|
||||
{
|
||||
[Fact]
|
||||
public void Refresh_ZeigtJungeOffeneNachreichungenUndFiltertAktuellAbwesende()
|
||||
{
|
||||
var date = new DateOnly(2026, 9, 25);
|
||||
var group = new LearningGroup { Name = "10c Chemie" };
|
||||
var amelia = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
|
||||
var carl = new Student { FirstName = "Carl", LastName = "Beispiel" };
|
||||
var oldMember = new Student { FirstName = "Dana", LastName = "Alt" };
|
||||
var previous = new ParticipationSession { GroupId = group.Id, Date = date.AddDays(-5) };
|
||||
var older = new ParticipationSession { GroupId = group.Id, Date = date.AddDays(-130) };
|
||||
var current = new ParticipationSession { GroupId = group.Id, Date = date };
|
||||
var memberships = new FakeMemberships([
|
||||
new GroupMembership { StudentId = amelia.Id, GroupId = group.Id },
|
||||
new GroupMembership { StudentId = ben.Id, GroupId = group.Id },
|
||||
new GroupMembership { StudentId = carl.Id, GroupId = group.Id },
|
||||
new GroupMembership { StudentId = oldMember.Id, GroupId = group.Id,
|
||||
Period = MembershipPeriod.Custom, JoinedAt = date.AddDays(-30), LeftAt = date.AddDays(-1) },
|
||||
]);
|
||||
var entries = new FakeEntries();
|
||||
entries.Add(new ParticipationEntry { SessionId = previous.Id, StudentId = amelia.Id,
|
||||
Homework = HomeworkStatus.MissingOverdue });
|
||||
var benEntry = new ParticipationEntry { SessionId = previous.Id, StudentId = ben.Id,
|
||||
Homework = HomeworkStatus.MissingOpen };
|
||||
entries.Add(benEntry);
|
||||
entries.Add(new ParticipationEntry { SessionId = previous.Id, StudentId = carl.Id,
|
||||
Homework = HomeworkStatus.SubmittedLate });
|
||||
entries.Add(new ParticipationEntry { SessionId = previous.Id, StudentId = oldMember.Id,
|
||||
Homework = HomeworkStatus.MissingOverdue });
|
||||
entries.Add(new ParticipationEntry { SessionId = older.Id, StudentId = ben.Id,
|
||||
Homework = HomeworkStatus.MissingOverdue });
|
||||
entries.Add(new ParticipationEntry { SessionId = current.Id, StudentId = ben.Id,
|
||||
Attendance = AttendanceStatus.Present });
|
||||
entries.Add(new ParticipationEntry { SessionId = current.Id, StudentId = amelia.Id,
|
||||
Attendance = AttendanceStatus.ExcusePending });
|
||||
|
||||
var vm = new TeachingModeOutstandingHomeworkViewModel(group.Id, date,
|
||||
new FakeStudents([amelia, ben, carl, oldMember]), memberships,
|
||||
new FakeSessions([previous, older, current]), entries);
|
||||
vm.SetCurrentSessionId(current.Id);
|
||||
vm.IsExpanded = true;
|
||||
|
||||
Assert.Equal(ben.FullName, Assert.Single(vm.Rows).StudentName);
|
||||
Assert.Equal("Offene Nachreichungen (1)", vm.Header);
|
||||
vm.IncludeAbsentStudents = true;
|
||||
Assert.Equal(2, vm.Rows.Count);
|
||||
Assert.Contains(vm.Rows, r => r.StudentName == amelia.FullName &&
|
||||
r.Status == HomeworkStatus.MissingOverdue);
|
||||
|
||||
vm.IncludeAbsentStudents = false;
|
||||
var currentAmelia = entries.GetBySessionAndStudent(current.Id, amelia.Id)!;
|
||||
currentAmelia.Attendance = AttendanceStatus.Present;
|
||||
entries.Save(currentAmelia);
|
||||
vm.Refresh();
|
||||
Assert.Equal(2, vm.Rows.Count);
|
||||
|
||||
benEntry.Homework = HomeworkStatus.SubmittedLate;
|
||||
entries.Save(benEntry);
|
||||
vm.Refresh();
|
||||
Assert.Equal(amelia.FullName, Assert.Single(vm.Rows).StudentName);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HomeworkStatus.MissingOpen, "submitted", HomeworkStatus.SubmittedLate)]
|
||||
[InlineData(HomeworkStatus.MissingOpen, "final", HomeworkStatus.MissingOverdue)]
|
||||
[InlineData(HomeworkStatus.MissingOpen, "partial", HomeworkStatus.PartialMissingOverdue)]
|
||||
[InlineData(HomeworkStatus.MissingOverdue, "submitted", HomeworkStatus.SubmittedLate)]
|
||||
[InlineData(HomeworkStatus.PartiallyCompleted, "submitted", HomeworkStatus.PartialSubmittedLate)]
|
||||
[InlineData(HomeworkStatus.PartiallyCompleted, "final", HomeworkStatus.PartialMissingOverdue)]
|
||||
[InlineData(HomeworkStatus.PartialMissingOverdue, "submitted", HomeworkStatus.PartialSubmittedLate)]
|
||||
public void Zeilenaktionen_SetzenPassendenEndstatus(HomeworkStatus start, string action, HomeworkStatus expected)
|
||||
{
|
||||
var (vm, entries, entry) = CreateSingle(start);
|
||||
vm.Refresh();
|
||||
var row = Assert.Single(vm.Rows);
|
||||
|
||||
var command = action switch
|
||||
{
|
||||
"submitted" => row.MarkSubmittedCommand,
|
||||
"final" => row.MarkFinalCommand,
|
||||
_ => row.MarkPartialCommand,
|
||||
};
|
||||
command.Execute(null);
|
||||
|
||||
var saved = entries.GetBySessionAndStudent(entry.SessionId, entry.StudentId)!;
|
||||
Assert.Equal(expected, saved.Homework);
|
||||
Assert.Equal(HomeworkDisplay.CountsAsMissing(expected), saved.HomeworkMissing);
|
||||
Assert.Equal(HomeworkDisplay.CountsAsMissing(expected), vm.Rows.Count == 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Zeilenaktionen_BietenNurSinnvolleOptionenAn()
|
||||
{
|
||||
var (vm, _, _) = CreateSingle(HomeworkStatus.MissingOverdue);
|
||||
vm.Refresh();
|
||||
var overdue = Assert.Single(vm.Rows);
|
||||
Assert.False(overdue.CanMarkFinal);
|
||||
Assert.True(overdue.CanMarkPartial);
|
||||
|
||||
(vm, _, _) = CreateSingle(HomeworkStatus.PartiallyCompleted);
|
||||
vm.Refresh();
|
||||
var partial = Assert.Single(vm.Rows);
|
||||
Assert.True(partial.CanMarkFinal);
|
||||
Assert.False(partial.CanMarkPartial);
|
||||
|
||||
(vm, _, _) = CreateSingle(HomeworkStatus.MissingOpen, isReadOnly: true);
|
||||
vm.Refresh();
|
||||
Assert.False(Assert.Single(vm.Rows).CanEdit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Undo_StelltVorherigenStatusWiederHer()
|
||||
{
|
||||
var (vm, entries, entry) = CreateSingle(HomeworkStatus.MissingOpen);
|
||||
var changed = 0;
|
||||
vm.OnHomeworkChanged = () => changed++;
|
||||
vm.Refresh();
|
||||
Assert.False(vm.UndoCommand.CanExecute(null));
|
||||
|
||||
vm.Rows[0].MarkSubmittedCommand.Execute(null);
|
||||
Assert.Empty(vm.Rows);
|
||||
Assert.NotNull(vm.LastChangeLabel);
|
||||
Assert.True(vm.UndoCommand.CanExecute(null));
|
||||
|
||||
vm.UndoCommand.Execute(null);
|
||||
var saved = entries.GetBySessionAndStudent(entry.SessionId, entry.StudentId)!;
|
||||
Assert.Equal(HomeworkStatus.MissingOpen, saved.Homework);
|
||||
Assert.True(saved.HomeworkMissing);
|
||||
Assert.Single(vm.Rows);
|
||||
Assert.Null(vm.LastChangeLabel);
|
||||
Assert.False(vm.UndoCommand.CanExecute(null));
|
||||
Assert.Equal(2, changed);
|
||||
}
|
||||
|
||||
private static (TeachingModeOutstandingHomeworkViewModel Vm, FakeEntries Entries, ParticipationEntry Entry)
|
||||
CreateSingle(HomeworkStatus status, bool isReadOnly = false)
|
||||
{
|
||||
var date = new DateOnly(2026, 9, 25);
|
||||
var group = new LearningGroup { Name = "10c Chemie" };
|
||||
var student = new Student { FirstName = "Ben", LastName = "Muster" };
|
||||
var session = new ParticipationSession { GroupId = group.Id, Date = date.AddDays(-5) };
|
||||
var entries = new FakeEntries();
|
||||
var entry = new ParticipationEntry { SessionId = session.Id, StudentId = student.Id,
|
||||
Homework = status, HomeworkMissing = true };
|
||||
entries.Add(entry);
|
||||
var vm = new TeachingModeOutstandingHomeworkViewModel(group.Id, date,
|
||||
new FakeStudents([student]),
|
||||
new FakeMemberships([new GroupMembership { StudentId = student.Id, GroupId = group.Id }]),
|
||||
new FakeSessions([session]), entries, isReadOnly);
|
||||
return (vm, entries, entry);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||
using LehrerApp.Core.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
@@ -28,4 +29,32 @@ public sealed class UntisNameMatchingTests
|
||||
{
|
||||
Assert.True(UntisNameMatching.NamesMatch("Gerste, Amelia", "Gerste Amelia"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildClassNameIndex_VerwendetDieselbeInstanzWieDieAuswahlliste()
|
||||
{
|
||||
var candidate = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||
var repositoryCopy = new Student
|
||||
{
|
||||
Id = candidate.Id, FirstName = candidate.FirstName, LastName = candidate.LastName,
|
||||
};
|
||||
|
||||
var index = UntisNameMatching.BuildClassNameIndex([candidate], [repositoryCopy]);
|
||||
|
||||
Assert.Same(candidate, index[UntisNameMatching.NameKey("Gerste Amelia")]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildClassNameIndex_GleicheNamenInVerschiedenenKlassenBleibenEindeutig()
|
||||
{
|
||||
var classStudent = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||
var otherStudent = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||
var candidates = new[] { classStudent, otherStudent };
|
||||
|
||||
Assert.Empty(UntisNameMatching.BuildNameIndex(candidates));
|
||||
var index = UntisNameMatching.BuildClassNameIndex(candidates,
|
||||
[new Student { Id = classStudent.Id, FirstName = "Amelia", LastName = "Gerste" }]);
|
||||
|
||||
Assert.Same(classStudent, index[UntisNameMatching.NameKey("Gerste Amelia")]);
|
||||
}
|
||||
}
|
||||
@@ -187,6 +187,45 @@ public sealed class UntisReportCacheServiceTests
|
||||
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)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/json"),
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||
using LehrerApp.Desktop.ViewModels.Students;
|
||||
using LehrerApp.Desktop.Views.Shared;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
/// Tests für Standardformulierungen, schülerabhängige Bausteine im Vorgang-Dialog, den WebUntis-Stand
|
||||
/// der Klassenlehrer-Vorgänge und die Wochentags-Ausrichtung des kompakten Monatskalenders.
|
||||
public sealed class VorgangBausteineTests
|
||||
{
|
||||
[Fact]
|
||||
public void KompakterKalender_BeginntInDerSpalteDesWochentags()
|
||||
{
|
||||
// 1. September 2026 ist ein Dienstag -> eine Leerzelle (Montag) davor.
|
||||
var days = Enumerable.Range(1, 30).Select(d => new ClassTeacherCompactCalendarDay(
|
||||
new DateOnly(2026, 9, d), "", "#00000000", "", false)).ToList();
|
||||
|
||||
var cells = CompactMonthCalendar.BuildCells(days);
|
||||
|
||||
Assert.True(cells[0].IsPlaceholder);
|
||||
Assert.Equal(new DateOnly(2026, 9, 1), cells[1].Day!.Date);
|
||||
Assert.Equal(31, cells.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KompakterKalender_MonatsbeginnAmMontag_OhneLeerzelle()
|
||||
{
|
||||
var days = new[] { new ClassTeacherCompactCalendarDay(new DateOnly(2026, 6, 1), "", "", "", false) };
|
||||
Assert.False(CompactMonthCalendar.BuildCells(days)[0].IsPlaceholder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Standardformulierung_WirdAlsZeileAngehaengt()
|
||||
{
|
||||
var vm = new VorgangDialogViewModel([new StudentOption(Guid.NewGuid(), "Anna")], null,
|
||||
phraseBlocks: VorgangPhraseBlocks.ForStudent(new DateOnly(2026, 9, 26))) { Description = "Notiz" };
|
||||
|
||||
vm.InsertPhraseCommand.Execute(vm.PhraseBlocks.First(p => p.Label == "Klassenleitung informiert"));
|
||||
|
||||
Assert.Equal("Notiz\n26.09.2026: Klassenleitung informiert.", vm.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SchuelerBausteine_FolgenDerAuswahlImDialog()
|
||||
{
|
||||
var anna = new StudentOption(Guid.NewGuid(), "Anna");
|
||||
var ben = new StudentOption(Guid.NewGuid(), "Ben");
|
||||
var vm = new VorgangDialogViewModel([anna, ben], null,
|
||||
studentQuickBlocks: ids => ids.Select(id => new VorgangQuickBlock(id == anna.Id ? "A" : "B", "")).ToList());
|
||||
|
||||
Assert.False(vm.HasQuickBlocks);
|
||||
vm.StudentOptions[1].IsSelected = true;
|
||||
Assert.Equal(["B"], vm.QuickBlocks.Select(b => b.Label));
|
||||
vm.StudentOptions[0].IsSelected = true;
|
||||
Assert.Equal(["A", "B"], vm.QuickBlocks.Select(b => b.Label));
|
||||
}
|
||||
|
||||
private static ClassAbsenceDaySummaryRow Absence(DateOnly date, string name, int periods, bool unexcused,
|
||||
bool fullDay = false, string reason = "Krankheit") => new(date, name, null, periods, periods * 45,
|
||||
["M"], [1], [unexcused ? "nicht entschuldigt" : "entschuldigt"], [reason], null, null, fullDay);
|
||||
|
||||
[Fact]
|
||||
public void KlassenlehrerStand_ZaehltFehlzeitenVerspaetungenUndKlassenbuch()
|
||||
{
|
||||
var student = new StudentOption(Guid.NewGuid(), "Beispiel Anna");
|
||||
var today = new DateOnly(2026, 9, 26);
|
||||
var absences = new[]
|
||||
{
|
||||
Absence(today.AddDays(-3), "Anna Beispiel", 6, unexcused: true, fullDay: true),
|
||||
Absence(today.AddDays(-5), "Anna Beispiel", 2, unexcused: false),
|
||||
Absence(today.AddDays(-6), "Anna Beispiel", 0, unexcused: false, reason: "Verspätung"),
|
||||
Absence(today.AddDays(-3), "Ben Fremd", 6, unexcused: true),
|
||||
};
|
||||
var register = new[]
|
||||
{
|
||||
new ClassTeacherClassRegisterRow(today.AddDays(-2), "D", "Anna Beispiel", "MUE", "Hausaufgaben fehlen", "Negativ", null),
|
||||
new ClassTeacherClassRegisterRow(today.AddDays(-1), "E", "Anna Beispiel", "SCH", "Lob", "Positiv", null),
|
||||
};
|
||||
|
||||
var facts = ClassTeacherStudentFacts.Build(student, "Anna Beispiel", "2026/27", today, absences, register);
|
||||
|
||||
Assert.Equal(8, facts.AbsentPeriods);
|
||||
Assert.Equal(1, facts.UnexcusedDays);
|
||||
Assert.Equal(2, facts.PartialAbsentPeriods);
|
||||
Assert.Equal(0, facts.UnexcusedPartialPeriods);
|
||||
Assert.Single(facts.LateDays);
|
||||
Assert.Equal(1, facts.NegativeRegisterCount);
|
||||
Assert.Single(facts.HomeworkEntries);
|
||||
Assert.Contains("1 ganzer Fehltag und 2 weitere Fehlstunden", facts.AbsenceShort);
|
||||
|
||||
var labels = facts.QuickBlocks(withName: true).Select(b => b.Label).ToList();
|
||||
Assert.Contains("Fehlzeiten · Beispiel Anna", labels);
|
||||
|
||||
var ctx = facts.TemplateContext(new Vorgang { Title = "Fehlzeiten", Tags = ["Absentismus"] });
|
||||
Assert.Equal([facts.AbsenceShort], ctx.SituationLines);
|
||||
var letter = VorgangDocumentationTemplates.Build(VorgangDocumentationTemplates.ParentLetter,
|
||||
new Vorgang { Title = "Fehlzeiten", Tags = ["Absentismus"] }, ctx)!;
|
||||
Assert.StartsWith("Sehr geehrte Erziehungsberechtigte von Anna Beispiel", letter.ParentLetterData!.DraftContent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KlassenlehrerStand_UnentschuldigteFehlstundeWirdNichtAlsFehltagBezeichnet()
|
||||
{
|
||||
var student = new StudentOption(Guid.NewGuid(), "Beispiel Anna");
|
||||
var today = new DateOnly(2026, 9, 28);
|
||||
var facts = ClassTeacherStudentFacts.Build(student, "Anna Beispiel", "2026/27", today,
|
||||
[Absence(today.AddDays(-4), "Anna Beispiel", 1, unexcused: true)], []);
|
||||
|
||||
Assert.Equal(0, facts.FullDays);
|
||||
Assert.Equal(0, facts.UnexcusedDays);
|
||||
Assert.Equal(1, facts.PartialAbsentPeriods);
|
||||
Assert.Equal(1, facts.UnexcusedPartialPeriods);
|
||||
Assert.Contains("0 ganze Fehltage und 1 weitere Fehlstunde", facts.AbsenceShort);
|
||||
Assert.Contains("unentschuldigt: 0 ganze Tage, 1 Fehlstunde", facts.AbsenceShort);
|
||||
Assert.Contains("1 Fehlstunde · Unentschuldigt", facts.AbsenceBlock);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Vorlage_KlassenleitungInformieren()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
var ctx = new VorgangTemplateContext(id, "Anna Beispiel", new DateOnly(2026, 9, 26), ["Fehlquote 25 %"],
|
||||
new Dictionary<string, VorgangSnapshot>());
|
||||
|
||||
var doc = VorgangDocumentationTemplates.Build(VorgangDocumentationTemplates.InformClassTeacher,
|
||||
new Vorgang { Title = "Fehlzeiten" }, ctx)!;
|
||||
|
||||
Assert.Equal(DocumentationType.Conversation, doc.Type);
|
||||
Assert.Equal(["Klassenleitung"], doc.Participants);
|
||||
Assert.Contains("Klassenleitung am 26.09.2026 informiert über:\n- Fehlquote 25 %", doc.Content);
|
||||
Assert.Equal(id, doc.StudentId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using LehrerApp.WebUntis;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class WebUntisHomeworkComparisonViewModelTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("Fehlende HA", "Buch vergessen", "Negativ", true)]
|
||||
[InlineData("Sonstiges", "HA nicht dabei", "Negativ", false)]
|
||||
[InlineData(null, "HA nicht dabei", "Negativ", true)]
|
||||
[InlineData("Hausaufgaben fehlen", null, "Negativ", true)]
|
||||
[InlineData("Verhalten", "Schüler war unruhig", "Negativ", false)]
|
||||
[InlineData("Hausaufgaben", "HA gemacht", "Positiv", false)]
|
||||
[InlineData("Sonstiges", "Schach gespielt", "Negativ", false)]
|
||||
public void IsMissingHomeworkEntry_ErkenntAuchDasWebUntisKuerzel(
|
||||
string? category, string? entryText, string group, bool expected)
|
||||
{
|
||||
var entry = new UntisClassRegisterEventDto("10c", 20260925, "Che", "Gerste Amelia",
|
||||
category, group, entryText);
|
||||
|
||||
Assert.Equal(expected, WebUntisHomeworkComparisonViewModel.IsMissingHomeworkEntry(entry));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Load_ZeigtFehlendeHaAuchOhneHausaufgabeImFreitext()
|
||||
{
|
||||
const string report = "Klasse\tDatum\tFach\tName\tBenutzer\tEintragskategorie\tKategoriegruppe\tText\r\n" +
|
||||
"10c\t25.09.26\tChe\tGerste Amelia\tlehrkraft\tFehlende HA\tNegativ\tChe: Buch vergessen\r\n" +
|
||||
"10c\t25.09.26\tChe\tGerste Amelia\tlehrkraft\tHausaufgaben\tPositiv\tChe: alles erledigt\r\n";
|
||||
var handler = new QueueHandler(
|
||||
Json("{\"result\":{\"sessionId\":\"s\"}}"),
|
||||
Json("{\"result\":[{\"id\":1,\"name\":\"2026/27\",\"startDate\":20260801,\"endDate\":20270731}]}"),
|
||||
Json("{\"data\":{\"finished\":true,\"error\":false," +
|
||||
"\"reportParams\":\"get=rpt.tmp&name=ClassregEventPerStudent&format=csv\"}}"),
|
||||
new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new ByteArrayContent(Encoding.UTF8.GetBytes(report)),
|
||||
});
|
||||
var settings = TestSupport.BuildWebUntisSettingsService();
|
||||
var credentials = new WebUntisCredentials("schule", "arche.webuntis.com", "lehrkraft", "geheim");
|
||||
settings.SetApiCredentials(credentials);
|
||||
await using var untis = new WebUntisIntegrationService(new HttpClient(handler), settings);
|
||||
await untis.ConnectAsync(credentials);
|
||||
var vm = new WebUntisHomeworkComparisonViewModel(untis, new FakeStudents([]),
|
||||
new FakeGroups([]), new FakeSubjects([]), new FakeMemberships([]),
|
||||
new FakeSessions([]), new FakeEntries(), new SchoolYearService())
|
||||
{
|
||||
StartDate = new DateTimeOffset(2026, 9, 24, 12, 0, 0, TimeSpan.Zero),
|
||||
EndDate = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero),
|
||||
};
|
||||
|
||||
await vm.LoadCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal("Gerste Amelia", Assert.Single(vm.Rows).UntisStudentName);
|
||||
Assert.Contains("1 passende Einträge von 2", vm.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadUndApply_TrenntBestehendenStatus_ZielstatusUndLokaleEintraege()
|
||||
{
|
||||
const string report = "Klasse\tDatum\tFach\tName\tBenutzer\tEintragskategorie\tKategoriegruppe\tText\r\n" +
|
||||
"10c\t25.09.26\tChe\tGerste Amelia\tlehrkraft\tFehlende HA\tNegativ\tChe: nicht gemacht\r\n" +
|
||||
"10c\t25.09.26\tChe\tMuster Ben\tlehrkraft\tFehlende HA\tNegativ\tChe: nicht gemacht\r\n";
|
||||
var handler = new QueueHandler(
|
||||
Json("{\"result\":{\"sessionId\":\"s\"}}"),
|
||||
Json("{\"result\":[{\"id\":1,\"name\":\"2026/27\",\"startDate\":20260801,\"endDate\":20270731}]}"),
|
||||
Json("{\"data\":{\"finished\":true,\"error\":false," +
|
||||
"\"reportParams\":\"get=rpt.tmp&name=ClassregEventPerStudent&format=csv\"}}"),
|
||||
new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new ByteArrayContent(Encoding.UTF8.GetBytes(report)),
|
||||
});
|
||||
var settings = TestSupport.BuildWebUntisSettingsService();
|
||||
var credentials = new WebUntisCredentials("schule", "arche.webuntis.com", "lehrkraft", "geheim");
|
||||
settings.SetApiCredentials(credentials);
|
||||
await using var untis = new WebUntisIntegrationService(new HttpClient(handler), settings);
|
||||
await untis.ConnectAsync(credentials);
|
||||
|
||||
var date = new DateOnly(2026, 9, 25);
|
||||
var schoolYear = new SchoolYearService();
|
||||
var chemistry = new Subject { Name = "Chemie", ShortName = "Che" };
|
||||
var biology = new Subject { Name = "Biologie", ShortName = "Bio" };
|
||||
var classGroup = new LearningGroup { Name = "10c", Type = GroupType.Class,
|
||||
SchoolYear = schoolYear.CurrentSchoolYear(date) };
|
||||
var chemistryGroup = new LearningGroup { Name = "Chemie 10c", Type = GroupType.Course,
|
||||
SubjectId = chemistry.Id, SchoolYear = classGroup.SchoolYear };
|
||||
var biologyGroup = new LearningGroup { Name = "Biologie 10c", Type = GroupType.Course,
|
||||
SubjectId = biology.Id, SchoolYear = classGroup.SchoolYear };
|
||||
var amelia = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
|
||||
var carl = new Student { FirstName = "Carl", LastName = "Beispiel" };
|
||||
var chemistrySession = new ParticipationSession { GroupId = chemistryGroup.Id, Date = date };
|
||||
var biologySession = new ParticipationSession { GroupId = biologyGroup.Id, Date = date };
|
||||
var memberships = new FakeMemberships([
|
||||
new GroupMembership { StudentId = amelia.Id, GroupId = chemistryGroup.Id },
|
||||
new GroupMembership { StudentId = amelia.Id, GroupId = biologyGroup.Id },
|
||||
new GroupMembership { StudentId = ben.Id, GroupId = chemistryGroup.Id },
|
||||
new GroupMembership { StudentId = carl.Id, GroupId = chemistryGroup.Id },
|
||||
]);
|
||||
var participation = new FakeEntries();
|
||||
participation.Add(new ParticipationEntry { SessionId = chemistrySession.Id, StudentId = amelia.Id,
|
||||
Homework = HomeworkStatus.MissingOpen, HomeworkMissing = true });
|
||||
participation.Add(new ParticipationEntry { SessionId = biologySession.Id, StudentId = amelia.Id,
|
||||
Homework = HomeworkStatus.PartiallyCompleted, HomeworkMissing = true });
|
||||
participation.Add(new ParticipationEntry { SessionId = chemistrySession.Id, StudentId = carl.Id,
|
||||
Homework = HomeworkStatus.MissingOverdue, HomeworkMissing = true });
|
||||
|
||||
var vm = new WebUntisHomeworkComparisonViewModel(untis,
|
||||
new FakeStudents([amelia, ben, carl]),
|
||||
new FakeGroups([classGroup, chemistryGroup, biologyGroup]),
|
||||
new FakeSubjects([chemistry, biology]), memberships,
|
||||
new FakeSessions([chemistrySession, biologySession]), participation, schoolYear)
|
||||
{
|
||||
StartDate = new DateTimeOffset(2026, 9, 24, 12, 0, 0, TimeSpan.Zero),
|
||||
EndDate = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero),
|
||||
};
|
||||
|
||||
await vm.LoadCommand.ExecuteAsync(null);
|
||||
|
||||
var existing = Assert.Single(vm.Rows, r => r.AssignedStudent?.Id == amelia.Id);
|
||||
Assert.False(existing.Selected);
|
||||
Assert.Equal(HomeworkDisplay.Label(HomeworkStatus.MissingOpen), existing.LocalStatus);
|
||||
Assert.Equal(HomeworkDisplay.Label(HomeworkStatus.MissingOpen), existing.SelectedStatusName);
|
||||
var newRow = Assert.Single(vm.Rows, r => r.AssignedStudent?.Id == ben.Id);
|
||||
Assert.True(newRow.Selected);
|
||||
Assert.Equal("Noch kein Status erfasst", newRow.LocalStatus);
|
||||
Assert.Equal(2, vm.LocalOnlyRows.Count);
|
||||
Assert.Contains(vm.LocalOnlyRows, r => r.StudentName == amelia.FullName && r.GroupName == biologyGroup.Name);
|
||||
Assert.Contains(vm.LocalOnlyRows, r => r.StudentName == carl.FullName && r.GroupName == chemistryGroup.Name);
|
||||
|
||||
newRow.AssignedStudent = carl;
|
||||
Assert.Single(vm.LocalOnlyRows);
|
||||
Assert.False(newRow.Selected);
|
||||
newRow.AssignedStudent = ben;
|
||||
Assert.Equal(2, vm.LocalOnlyRows.Count);
|
||||
newRow.SelectedStatusName = HomeworkDisplay.Label(HomeworkStatus.SubmittedLate);
|
||||
vm.ApplyCommand.Execute(null);
|
||||
|
||||
var saved = participation.GetBySessionAndStudent(chemistrySession.Id, ben.Id);
|
||||
Assert.Equal(HomeworkStatus.SubmittedLate, saved?.Homework);
|
||||
Assert.False(saved?.HomeworkMissing);
|
||||
Assert.Equal(HomeworkDisplay.Label(HomeworkStatus.SubmittedLate), newRow.LocalStatus);
|
||||
Assert.False(newRow.Selected);
|
||||
Assert.Equal(HomeworkStatus.MissingOpen,
|
||||
participation.GetBySessionAndStudent(chemistrySession.Id, amelia.Id)?.Homework);
|
||||
}
|
||||
|
||||
private static HttpResponseMessage Json(string json) => new(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/json"),
|
||||
};
|
||||
|
||||
private sealed class QueueHandler(params HttpResponseMessage[] responses) : HttpMessageHandler
|
||||
{
|
||||
private readonly Queue<HttpResponseMessage> _responses = new(responses);
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
|
||||
CancellationToken cancellationToken) => Task.FromResult(_responses.Dequeue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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.Workload;
|
||||
using LehrerApp.Desktop.Views;
|
||||
using LehrerApp.Desktop.Views.Shared;
|
||||
using LehrerApp.Desktop.Views.Workload;
|
||||
using LehrerApp.Sync;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -28,6 +29,7 @@ public class App : Application
|
||||
private static bool _exitHandlerAttached;
|
||||
private static Task _initialPolls = Task.CompletedTask;
|
||||
private static readonly CancellationTokenSource StartupCancellation = new();
|
||||
private static DispatcherTimer? _homeworkOverdueTimer;
|
||||
|
||||
public override void Initialize() => AvaloniaXamlLoader.Load(this);
|
||||
|
||||
@@ -100,6 +102,7 @@ public class App : Application
|
||||
splash?.SetProgress(60, "Papierkorb aufräumen …");
|
||||
await Task.Run(() => Services.GetRequiredService<ITrashRepository>()
|
||||
.PurgeOlderThan(DateTime.UtcNow.AddDays(-30)));
|
||||
await AdvanceHomeworkAsync();
|
||||
|
||||
if (!_exitHandlerAttached)
|
||||
{
|
||||
@@ -126,6 +129,7 @@ public class App : Application
|
||||
main.EnableFinalSync(syncEngine);
|
||||
desktop.MainWindow = main;
|
||||
main.Show();
|
||||
StartHomeworkOverdueTimer();
|
||||
splash?.SetProgress(100, "Bereit");
|
||||
windowToClose?.Close();
|
||||
AppBootstrapper.Logger.Info($"Start: Hauptfenster nach {timer.ElapsedMilliseconds} ms geöffnet.");
|
||||
@@ -152,6 +156,30 @@ public class App : Application
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task AdvanceHomeworkAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var changed = await Task.Run(() => Services.GetRequiredService<HomeworkOverdueService>()
|
||||
.Advance(DateOnly.FromDateTime(DateTime.Today)));
|
||||
if (changed > 0) AppBootstrapper.Logger.Info($"{changed} offene Hausaufgaben als nicht nachgereicht markiert.");
|
||||
}
|
||||
catch (Exception ex) { AppBootstrapper.Logger.Error("Hausaufgaben-Fristprüfung fehlgeschlagen.", ex); }
|
||||
}
|
||||
|
||||
private static void StartHomeworkOverdueTimer()
|
||||
{
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromHours(1) };
|
||||
timer.Tick += async (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
await AdvanceHomeworkAsync();
|
||||
if (_serviceProvider is not null) timer.Start();
|
||||
};
|
||||
_homeworkOverdueTimer = timer;
|
||||
timer.Start();
|
||||
}
|
||||
|
||||
/// <summary>Wechselt die Darstellung sofort, ohne Neustart (12.4) — Avalonia stylt den
|
||||
/// gesamten sichtbaren Baum automatisch neu, sobald sich <see cref="ThemeVariant"/>
|
||||
/// ändert.</summary>
|
||||
@@ -165,6 +193,7 @@ public class App : Application
|
||||
|
||||
private static void DisposeServices()
|
||||
{
|
||||
_homeworkOverdueTimer?.Stop();
|
||||
var serviceProvider = Interlocked.Exchange(ref _serviceProvider, null);
|
||||
if (serviceProvider is null) return;
|
||||
|
||||
@@ -206,10 +235,12 @@ public class App : Application
|
||||
var dash = Services.GetRequiredService<DashboardViewModel>();
|
||||
dash.OnNavigateToGroup = id => main.NavigateToGroupDetail(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.OnNavigateToExam = id => main.NavigateToGroupDetail(id, 4); // Tab "Klausuren"
|
||||
dash.OnNavigateToUnplannedLesson = id => main.NavigateToGroupDetail(id, 6); // Tab "Planung"
|
||||
dash.OnAddMissingTeachingTime = item => ShowMissingTeachingTimeDialog(item, dash);
|
||||
dash.OnPickSnoozeDuration = ShowSnoozeDurationDialog;
|
||||
|
||||
var examsOverview = Services.GetRequiredService<ViewModels.Exams.ExamsOverviewViewModel>();
|
||||
examsOverview.OnNavigateToGroups = () => main.NavigateToCommand.Execute(NavItem.Groups);
|
||||
@@ -265,6 +296,16 @@ public class App : Application
|
||||
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)
|
||||
{
|
||||
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime
|
||||
|
||||
@@ -122,6 +122,7 @@ public static class AppBootstrapper
|
||||
services.AddSingleton<PdfExportService>();
|
||||
services.AddSingleton<ITemplateLoader, TemplateLoader>();
|
||||
services.AddSingleton<ITemplateRenderer, QuestTemplateRenderer>();
|
||||
services.AddSingleton<ITemplateBatchRenderer, QuestTemplateRenderer>();
|
||||
services.AddSingleton(_ => new TemplateStore(appData));
|
||||
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<IGroupRepository, GroupRepository>();
|
||||
services.AddSingleton<ISeatingPlanRepository, SeatingPlanRepository>();
|
||||
services.AddSingleton<IStudentGroupPlanRepository, StudentGroupPlanRepository>();
|
||||
services.AddSingleton<ITrashRepository, TrashRepository>();
|
||||
services.AddSingleton<IGroupMembershipRepository, GroupMembershipRepository>();
|
||||
services.AddSingleton<IExamRepository, ExamRepository>();
|
||||
@@ -163,11 +165,13 @@ public static class AppBootstrapper
|
||||
services.AddSingleton<IGradeRepository, GradeRepository>();
|
||||
services.AddSingleton<IGradingSchemeRepository, GradingSchemeRepository>();
|
||||
services.AddSingleton<IReportGradeRepository, ReportGradeRepository>();
|
||||
services.AddSingleton<IInterimGradeRepository, InterimGradeRepository>();
|
||||
services.AddSingleton<IGradingKeyTemplateRepository, GradingKeyTemplateRepository>();
|
||||
services.AddSingleton<IUnitRepository, UnitRepository>();
|
||||
services.AddSingleton<ILessonRepository, LessonRepository>();
|
||||
services.AddSingleton<IDocumentationRepository, DocumentationRepository>();
|
||||
services.AddSingleton<IVorgangRepository, VorgangRepository>();
|
||||
services.AddSingleton<IDashboardWarningSnoozeRepository, DashboardWarningSnoozeRepository>();
|
||||
services.AddSingleton<IWorkTaskRepository, WorkTaskRepository>();
|
||||
services.AddSingleton<ITimeEntryRepository, TimeEntryRepository>();
|
||||
services.AddSingleton<IParticipationSessionRepository, ParticipationSessionRepository>();
|
||||
@@ -197,6 +201,7 @@ public static class AppBootstrapper
|
||||
services.AddSingleton<GradingService>();
|
||||
services.AddSingleton<CompetencyAnalysisService>();
|
||||
services.AddSingleton<SchoolYearService>();
|
||||
services.AddSingleton<HomeworkOverdueService>();
|
||||
services.AddSingleton<GroupRolloverService>();
|
||||
services.AddSingleton<PublicHolidayService>();
|
||||
services.AddSingleton(_ => new SchoolCalendarSettingsService(appData));
|
||||
@@ -205,7 +210,9 @@ public static class AppBootstrapper
|
||||
services.AddSingleton(_ => new DashboardSettingsService(appData));
|
||||
services.AddSingleton(_ => new PatternScoreSettingsService(appData));
|
||||
services.AddSingleton(_ => new WindowSettingsService(appData));
|
||||
services.AddSingleton(_ => new ExamGradingSettingsService(appData));
|
||||
services.AddSingleton(_ => new AppearanceSettingsService(appData));
|
||||
services.AddSingleton(_ => new TeacherSettingsService(appData));
|
||||
services.AddSingleton<PlanningExchangeService>();
|
||||
|
||||
// ── KI-Unterstützung (4.5.9, optional – nur wenn in den Einstellungen aktiviert) ──────
|
||||
@@ -231,6 +238,7 @@ public static class AppBootstrapper
|
||||
services.AddSingleton<GroupMembershipTools>();
|
||||
services.AddSingleton<LetterTemplateTools>();
|
||||
services.AddSingleton<StudentAttendanceCalendarService>();
|
||||
services.AddSingleton<StudentReportService>();
|
||||
services.AddSingleton<CompetencyTools>();
|
||||
services.AddSingleton<GroupTools>();
|
||||
services.AddSingleton<ParticipationTools>();
|
||||
@@ -356,6 +364,8 @@ public static class AppBootstrapper
|
||||
// Transient: neue Instanz pro Navigation (für Detailseiten)
|
||||
services.AddTransient<GroupDetailViewModel>();
|
||||
services.AddTransient<StudentDetailViewModel>();
|
||||
services.AddTransient<StudentWarningEvidenceService>();
|
||||
services.AddTransient<StudentVorgaengeViewModel>();
|
||||
services.AddTransient<GroupOverviewViewModel>();
|
||||
services.AddTransient<ParticipationTabViewModel>();
|
||||
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.Fonts.Inter" />
|
||||
<PackageReference Include="Avalonia.Controls.DataGrid" />
|
||||
<PackageReference Include="Avalonia.Labs.Lottie" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<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.");
|
||||
}
|
||||
|
||||
public async Task<decimal> GetBalanceAsync(string token)
|
||||
{
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, "status.php");
|
||||
req.Headers.Authorization = new("Bearer", token);
|
||||
public async Task<decimal> GetBalanceAsync(string token) =>
|
||||
(await GetAccountBalanceAsync(token)).BalanceUsd;
|
||||
|
||||
HttpResponseMessage resp;
|
||||
try { resp = await http.SendAsync(req); }
|
||||
catch (HttpRequestException)
|
||||
public async Task<AiAccountBalance> GetAccountBalanceAsync(string token)
|
||||
{
|
||||
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte Internetverbindung prüfen.");
|
||||
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.");
|
||||
}
|
||||
}
|
||||
|
||||
if (resp.StatusCode == HttpStatusCode.Unauthorized)
|
||||
throw new AiBackendException("Anmeldung abgelaufen. Bitte in den Einstellungen erneut anmelden.");
|
||||
if (!resp.IsSuccessStatusCode)
|
||||
throw new AiBackendException("Guthaben konnte nicht abgerufen 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());
|
||||
}
|
||||
|
||||
var result = await resp.Content.ReadFromJsonAsync<BalanceResult>(JsonOptions);
|
||||
return result?.BalanceUsd ?? 0m;
|
||||
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;
|
||||
try { resp = await http.SendAsync(req); }
|
||||
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException)
|
||||
{
|
||||
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte später erneut versuchen.");
|
||||
}
|
||||
if (resp.IsSuccessStatusCode) return resp;
|
||||
var status = resp.StatusCode;
|
||||
resp.Dispose();
|
||||
throw new AiBackendException(status switch
|
||||
{
|
||||
HttpStatusCode.Unauthorized => "Anmeldung abgelaufen. Bitte in den Einstellungen erneut anmelden.",
|
||||
HttpStatusCode.NotFound when path.StartsWith("api/v1/usage") =>
|
||||
"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>
|
||||
@@ -695,7 +719,6 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
}
|
||||
|
||||
private class LoginResult { public string Token { get; set; } = ""; }
|
||||
private class BalanceResult { public decimal BalanceUsd { get; set; } }
|
||||
private class BackendErrorResult
|
||||
{
|
||||
public string? Error { get; set; }
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>Verbrauch einer Aktion im Zeitraum, z. B. „Text korrigieren“ oder eine Planung der LehrerApp (alle Apps am selben Backend).</summary>
|
||||
/// <param name="Operation">Funktion der Arbeitsblatt-API; null bei Aktionen anderer Apps.</param>
|
||||
/// <param name="ChargedEur">Nur, wenn für jeden Aufruf der Euro-Gegenwert dokumentiert ist; sonst null (der Dienst schätzt nichts).</param>
|
||||
public sealed record AiUsageGroup(string ActionId, string Label, string? Operation, int Calls, decimal ChargedUsd, decimal? ChargedEur);
|
||||
|
||||
/// <summary>Ein berechneter Aufruf. <see cref="At"/> ist die Uhrzeit der Datenbank des Dienstes, ohne Zeitzone.</summary>
|
||||
public sealed record AiUsageEntry(DateTime At, string ActionId, string Label, string? Operation, string Status, decimal ChargedUsd, decimal? ChargedEur);
|
||||
|
||||
/// <param name="SpellcheckGranted">Ob die Rechtschreibprüfung über das Backend freigegeben ist; null, wenn der Dienst es nicht meldet.</param>
|
||||
public sealed record AiUsageReport(int Days, DateTime From, DateTime To, int Calls, decimal ChargedUsd, decimal? ChargedEur,
|
||||
IReadOnlyList<AiUsageGroup> ByAction, IReadOnlyList<AiUsageEntry> Entries, bool EntriesTruncated, bool? SpellcheckGranted)
|
||||
{
|
||||
/// <summary>
|
||||
/// Liest die Antwort von <c>api/v1/usage.php</c>. Unbekannte zusätzliche Felder werden übergangen (der Dienst darf wachsen), fehlende oder
|
||||
/// unplausible Pflichtfelder sind ein Fehler.
|
||||
/// </summary>
|
||||
public static AiUsageReport Parse(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 16 });
|
||||
var root = document.RootElement;
|
||||
Need(root.GetProperty("apiVersion").GetString() == "1" && root.GetProperty("schema").GetString() == "lehrerbackend.usage.v1");
|
||||
var period = root.GetProperty("period");
|
||||
var days = period.GetProperty("days").GetInt32();
|
||||
var totals = root.GetProperty("totals");
|
||||
var groups = new List<AiUsageGroup>();
|
||||
foreach (var item in root.GetProperty("byAction").EnumerateArray())
|
||||
{
|
||||
Need(groups.Count < 256);
|
||||
groups.Add(new(Text(item, "actionId", 64), Text(item, "label", 200), Operation(item), item.GetProperty("calls").GetInt32(),
|
||||
RequiredMoney(item, "chargedUsd"), Money(item, "chargedEur")));
|
||||
}
|
||||
var entries = new List<AiUsageEntry>();
|
||||
foreach (var item in root.GetProperty("entries").EnumerateArray())
|
||||
{
|
||||
Need(entries.Count < 1000);
|
||||
entries.Add(new(Date(item.GetProperty("at").GetString()), Text(item, "actionId", 64), Text(item, "label", 200), Operation(item), Text(item, "status", 32),
|
||||
RequiredMoney(item, "chargedUsd"), Money(item, "chargedEur")));
|
||||
}
|
||||
bool? spellcheck = root.TryGetProperty("features", out var features) && features.TryGetProperty("spellcheck", out var flag) && flag.ValueKind is JsonValueKind.True or JsonValueKind.False
|
||||
? flag.GetBoolean() : null;
|
||||
var calls = totals.GetProperty("calls").GetInt32();
|
||||
Need(days is >= 1 and <= 366 && calls >= 0 && groups.All(g => g.Calls >= 0 && g.ChargedUsd >= 0 && g.ChargedEur is null or >= 0) && entries.All(e => e.ChargedUsd >= 0));
|
||||
return new(days, Date(period.GetProperty("from").GetString()), Date(period.GetProperty("to").GetString()), calls, RequiredMoney(totals, "chargedUsd"), Money(totals, "chargedEur"),
|
||||
groups, entries, root.GetProperty("entriesTruncated").GetBoolean(), spellcheck);
|
||||
}
|
||||
catch (Exception e) when (e is JsonException or InvalidOperationException or KeyNotFoundException or FormatException or ArgumentException or OverflowException)
|
||||
{ throw new AiBackendException("Die Verbrauchsdaten des KI-Dienstes konnten nicht verarbeitet werden."); }
|
||||
}
|
||||
|
||||
private static void Need(bool condition) { if (!condition) throw new FormatException(); }
|
||||
|
||||
private static string Text(JsonElement item, string name, int max)
|
||||
{
|
||||
var value = item.GetProperty(name).GetString();
|
||||
Need(!string.IsNullOrWhiteSpace(value) && value.Length <= max);
|
||||
return value!;
|
||||
}
|
||||
|
||||
private static string? Operation(JsonElement item) =>
|
||||
item.TryGetProperty("operation", out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
||||
|
||||
private static decimal RequiredMoney(JsonElement item, string name) =>
|
||||
Money(item, name) ?? throw new FormatException();
|
||||
|
||||
private static decimal? Money(JsonElement item, string name)
|
||||
{
|
||||
if (!item.TryGetProperty(name, out var value) || value.ValueKind == JsonValueKind.Null) return null;
|
||||
// Dezimaltext mit höchstens sechs Nachkommastellen wie im ganzen Vertrag, nie eine Fließkommazahl
|
||||
var text = value.GetString();
|
||||
Need(text is not null && System.Text.RegularExpressions.Regex.IsMatch(text, @"^\d{1,9}(\.\d{1,6})?$"));
|
||||
return decimal.Parse(text!, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static DateTime Date(string? text)
|
||||
{
|
||||
Need(DateTime.TryParseExact(text, "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _));
|
||||
return DateTime.ParseExact(text!, "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.Globalization;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using LehrerApp.Templating;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>Platzhalterwerte für Klausur-Deckblätter (Vorlagen mit
|
||||
/// <c>report-type=exam-cover</c>): die Standardwerte der Elternbriefe (Student.*, Group.Name, …)
|
||||
/// plus Exam.*, Result.* und die Punktetabelle. Alle Punktwerte gelten für die Fassung, die der
|
||||
/// Schüler geschrieben hat.</summary>
|
||||
public static class ExamCoverPlaceholderBuilder
|
||||
{
|
||||
/// <summary>Stehen statt Punkten bzw. Note auf dem Blatt, solange nichts eingetragen wird —
|
||||
/// als Linie zum Ausfüllen von Hand.</summary>
|
||||
public const string BlankPoints = "_________", BlankGrade = "_____";
|
||||
|
||||
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
|
||||
|
||||
/// <param name="result">Ergebnis des Schülers oder null. Punkte und Note werden nur
|
||||
/// eingetragen, wenn <paramref name="fillResults"/> gesetzt und das Ergebnis korrigiert ist.</param>
|
||||
/// <param name="studentNiveau">Niveau des Schülers in dieser Lerngruppe, falls die Arbeit
|
||||
/// selbst keinem Niveau zugeordnet ist.</param>
|
||||
/// <param name="title">Titel für das Deckblatt, falls er vom internen Klausurtitel abweichen
|
||||
/// soll; null oder leer nimmt den Klausurtitel.</param>
|
||||
public static Dictionary<string, PlaceholderValue> Build(Exam exam, LearningGroup group, string subjectName,
|
||||
Student student, ExamResult? result, bool fillResults, GradingService grading, LoadedTemplate template,
|
||||
DateOnly today, Niveau? studentNiveau = null, string teacherAbbreviation = "",
|
||||
string? title = null, Exam? original = null, ExamResult? originalResult = null,
|
||||
InterimGrade? interim = null)
|
||||
{
|
||||
var tasks = exam.Tasks.OrderBy(t => t.Nr).ToList();
|
||||
var variant = result?.Variant ?? ExamVariant.A;
|
||||
var maximum = ExamScoringService.Maximum(tasks, variant);
|
||||
var filled = fillResults && ExamCoverSheetService.IsCorrected(result);
|
||||
|
||||
var values = LetterPlaceholderBuilder.BuildStandardValues(student, contact: null, group, today, "", "");
|
||||
values["Group.GradeLevel"] = new TextValue(group.GradeLevel > 0 ? group.GradeLevel.ToString() : "");
|
||||
values["Subject.Name"] = new TextValue(subjectName);
|
||||
values["Exam.Title"] = new TextValue(string.IsNullOrWhiteSpace(title) ? exam.Title : title.Trim());
|
||||
values["Exam.Date"] = new DateValue(exam.Date);
|
||||
values["Exam.Number"] = new TextValue(exam.ExamNumber?.ToString() ?? "");
|
||||
values["Exam.Kind"] = new TextValue(exam.Kind.Label());
|
||||
values["Exam.Niveau"] = new TextValue(exam.Niveau.HasValue ? NiveauDisplay.ToName(exam.Niveau) : "");
|
||||
values["Exam.Course"] = new TextValue(CourseLabel(group, exam.Niveau ?? studentNiveau));
|
||||
values["Teacher.Abbreviation"] = new TextValue(teacherAbbreviation.Trim());
|
||||
values["Exam.Variant"] = new TextValue(tasks.Any(t => t.Variant is not null) ? variant.ToString() : "");
|
||||
values["Exam.MaxPoints"] = new TextValue(Format(maximum));
|
||||
values["Exam.ApprovalDate"] = new TextValue(Format(exam.ApprovalGrantedAt));
|
||||
values["Exam.AnnouncedDate"] = new TextValue(Format(exam.AnnouncedAt));
|
||||
values["Exam.ReturnDate"] = new TextValue(Format(exam.ReturnedAt));
|
||||
values["Result.Points"] = new TextValue(filled ? Format(result!.TotalPoints) : BlankPoints);
|
||||
values["Result.Percent"] = new TextValue(filled && maximum > 0
|
||||
? (result!.TotalPoints / maximum).ToString("0 %", German) : "");
|
||||
values["Result.Grade"] = new TextValue(filled
|
||||
? result!.Grade ?? grading.CalculateGrade(result.TotalPoints, maximum, exam.GradingKey) : BlankGrade);
|
||||
|
||||
// Ohne Box in der Vorlage gibt es nichts zu zeichnen (die Tabelle ist optional).
|
||||
values[ExamPointsTableDrawingBuilder.PlaceholderName] =
|
||||
LetterPlaceholderBuilder.FindDeclaredDrawingBox(template, ExamPointsTableDrawingBuilder.PlaceholderName) is { } box
|
||||
? ExamPointsTableDrawingBuilder.Build(
|
||||
ExamCoverSheetService.Columns(tasks, variant, filled ? result!.Points : null),
|
||||
box.Width, box.MillimeterScale)
|
||||
: new DrawingValue([], 0);
|
||||
values[ReportTextDrawing.RepeatInfo] = DrawingBoxLocator.Find(template, ReportTextDrawing.RepeatInfo) is null
|
||||
? new DrawingValue([], 0) : GradeReportDrawingBuilder.Repeat(exam, original, originalResult, template);
|
||||
values[ReportTextDrawing.InterimGrades] = interim is null
|
||||
? new DrawingValue([], 0) : GradeReportDrawingBuilder.Interim(interim, template);
|
||||
return values;
|
||||
}
|
||||
|
||||
/// <summary>"E-Kurs" / "G-Kurs" für die äußere Differenzierung; leer im Klassenverband und
|
||||
/// ohne E-/G-Zuordnung.</summary>
|
||||
public static string CourseLabel(LearningGroup group, Niveau? niveau) =>
|
||||
group.Type == GroupType.Class ? "" : niveau switch
|
||||
{
|
||||
Niveau.E => "E-Kurs",
|
||||
Niveau.G => "G-Kurs",
|
||||
_ => "",
|
||||
};
|
||||
|
||||
private static string Format(double value) => value.ToString("0.##", German);
|
||||
private static string Format(DateOnly? date) => date?.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) ?? "";
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Avalonia.Controls;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using LehrerApp.Desktop.Views.Groups;
|
||||
using LehrerApp.Templating;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>Öffnet den Deckblatt-Dialog zu einer Klausur — ein Einstieg für die Klausuren-
|
||||
/// Hauptseite und den Klausuren-Tab der Lerngruppe.</summary>
|
||||
public static class ExamCoverSheetDialogs
|
||||
{
|
||||
public static async Task ShowAsync(Control source, Exam exam)
|
||||
{
|
||||
var group = App.Services.GetRequiredService<IGroupRepository>().GetById(exam.GroupId);
|
||||
if (group is null || TopLevel.GetTopLevel(source) is not Window owner) return;
|
||||
var subject = group.SubjectId is { } subjectId
|
||||
? App.Services.GetRequiredService<ISubjectRepository>().GetById(subjectId)?.Name ?? ""
|
||||
: "";
|
||||
var vm = new ExamCoverSheetDialogViewModel(exam, group, subject,
|
||||
App.Services.GetRequiredService<IStudentRepository>(),
|
||||
App.Services.GetRequiredService<IGroupMembershipRepository>(),
|
||||
App.Services.GetRequiredService<IExamResultRepository>(),
|
||||
App.Services.GetRequiredService<GradingService>(),
|
||||
[App.Services.GetRequiredService<TemplateStore>(), App.Services.GetRequiredService<WorksheetTemplateStore>().Store],
|
||||
App.Services.GetRequiredService<ITemplateBatchRenderer>(),
|
||||
App.Services.GetRequiredService<TeacherSettingsService>().LoadAbbreviation(),
|
||||
App.Services.GetRequiredService<IExamRepository>(),
|
||||
App.Services.GetRequiredService<IInterimGradeRepository>());
|
||||
await new ExamCoverSheetDialog { DataContext = vm }.ShowDialog(owner);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Templating;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>Brücke von den Klausurdaten zur Punktetabelle des Deckblatts. Gezeichnet wird in
|
||||
/// <see cref="ExamPointsTableDrawing"/> (Vorlagenbibliothek), damit der Vorlagen-Designer dieselbe
|
||||
/// Tabelle in der Vorschau zeigt.</summary>
|
||||
public static class ExamPointsTableDrawingBuilder
|
||||
{
|
||||
public const string PlaceholderName = ExamPointsTableDrawing.PlaceholderName;
|
||||
|
||||
public static DrawingValue Build(IReadOnlyList<ExamCoverTaskColumn> columns, float contentWidth = 170,
|
||||
float millimeterScale = 1) =>
|
||||
ExamPointsTableDrawing.Build(
|
||||
columns.Select(c => new ExamPointsTableColumn(c.Number, c.MaxPoints, c.IsBonus, c.AchievedPoints)).ToList(),
|
||||
contentWidth, millimeterScale);
|
||||
|
||||
public static int ColumnsPerBlock(float contentWidth, float millimeterScale = 1) =>
|
||||
ExamPointsTableDrawing.ColumnsPerBlock(contentWidth, millimeterScale);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Templating;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
public static class GradeReportDrawingBuilder
|
||||
{
|
||||
public static DrawingValue Interim(InterimGrade grade, LoadedTemplate template) =>
|
||||
Text(template, ReportTextDrawing.InterimGrades, "Vorläufiger Notenzwischenstand",
|
||||
[
|
||||
$"Stichtag: {grade.Date:dd.MM.yyyy} · {grade.Occasion}",
|
||||
$"Mündlich: {Value(grade.OralValue)}",
|
||||
$"Schriftlich: {Value(grade.WrittenValue)}",
|
||||
$"Vorläufige Zeugnisnote: {Value(grade.OverallValue)}",
|
||||
"Dieser Zwischenstand ist keine festgeschriebene Zeugnisnote.",
|
||||
]);
|
||||
|
||||
public static DrawingValue Repeat(Exam exam, Exam? original, ExamResult? originalResult,
|
||||
LoadedTemplate template)
|
||||
{
|
||||
if (exam.RepeatOfExamId is null) return new DrawingValue([], 0);
|
||||
if (original is null || original.Id != exam.RepeatOfExamId || original.GroupId != exam.GroupId)
|
||||
throw new InvalidDataException("Die verknüpfte erste Arbeit ist nicht verfügbar.");
|
||||
var rule = exam.IsSupportWork ? "Die Förderarbeit ersetzt die erste Arbeit. Liegen beide Noten vor, zählt die erste Arbeit."
|
||||
: exam.IsMakeUp ? "Die Nachschreibarbeit ersetzt die versäumte erste Arbeit. Liegen beide Noten vor, zählt die erste Arbeit."
|
||||
: exam.RepeatGradeRule switch
|
||||
{
|
||||
RepeatGradeRule.Repeat => "Für die Bewertung zählt die Note der Wiederholungsarbeit.",
|
||||
RepeatGradeRule.Original => "Für die Bewertung zählt die Note der ersten Arbeit.",
|
||||
_ => "Für die Bewertung zählt die bessere Note aus beiden Arbeiten.",
|
||||
};
|
||||
var grade = originalResult?.Grade;
|
||||
if (string.IsNullOrWhiteSpace(grade) && ExamCoverSheetService.IsCorrected(originalResult))
|
||||
grade = new GradingService().CalculateGrade(originalResult!.TotalPoints,
|
||||
ExamScoringService.Maximum(original.Tasks, originalResult.Variant), original.GradingKey);
|
||||
var firstGrade = originalResult is { Absent: true } ? "abwesend" : Value(grade);
|
||||
return Text(template, ReportTextDrawing.RepeatInfo,
|
||||
exam.IsSupportWork ? "Förderarbeit" : exam.IsMakeUp ? "Nachschreibarbeit" : "Wiederholungsarbeit",
|
||||
[$"Erste Arbeit: {original.Title} vom {original.Date:dd.MM.yyyy}",
|
||||
$"Note der ersten Arbeit: {firstGrade}", rule]);
|
||||
}
|
||||
|
||||
public static DrawingValue Text(LoadedTemplate template, string name, string title, IEnumerable<string> paragraphs)
|
||||
{
|
||||
if (DrawingBoxLocator.Find(template, name) is not { } box) return new DrawingValue([], 0);
|
||||
return ReportTextDrawing.Build(title, paragraphs, box.Width, box.MillimeterScale, box.Height, box.IsFixed);
|
||||
}
|
||||
|
||||
private static string Value(string? value) => string.IsNullOrWhiteSpace(value) ? "nicht erfasst" : value;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>Schließt nicht nachgereichte Hausaufgaben 14 Kalendertage nach der Unterrichtsstunde.
|
||||
/// Nur noch offene Nachreichungen werden geändert; andere Stati und archivierte Gruppen bleiben
|
||||
/// unangetastet.</summary>
|
||||
public sealed class HomeworkOverdueService(
|
||||
IGroupRepository groups, IParticipationSessionRepository sessions,
|
||||
IParticipationRepository participation)
|
||||
{
|
||||
public const int GracePeriodDays = 14;
|
||||
|
||||
public int Advance(DateOnly today)
|
||||
{
|
||||
var cutoff = today.AddDays(-GracePeriodDays);
|
||||
var activeGroupIds = groups.GetAll().Where(g => g.IsActive).Select(g => g.Id).ToHashSet();
|
||||
var changed = 0;
|
||||
foreach (var session in sessions.GetAll()
|
||||
.Where(s => s.Date <= cutoff && activeGroupIds.Contains(s.GroupId)))
|
||||
foreach (var entry in participation.GetBySession(session.Id))
|
||||
{
|
||||
if (entry.Homework != HomeworkStatus.MissingOpen &&
|
||||
!(entry.Homework is null && entry.HomeworkMissing)) continue;
|
||||
entry.Homework = HomeworkStatus.MissingOverdue;
|
||||
entry.HomeworkMissing = true;
|
||||
participation.Save(entry);
|
||||
changed++;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
@@ -51,34 +51,8 @@ public static class LetterPlaceholderBuilder
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>Tatsächliche DRAWBOX/FLOWDRAWBOX-Größe eines Platzhalters (in der Maßeinheit der
|
||||
/// Vorlage) plus dem Umrechnungsfaktor "1mm in dieser Maßeinheit". DrawingValue-Builder wie
|
||||
/// <see cref="StudentAttendanceCalendarDrawingBuilder"/> entwerfen ihr Raster in Millimetern;
|
||||
/// ohne MillimeterScale bliebe das bei einer in "pt" (statt "mm") deklarierten Vorlage viel zu
|
||||
/// klein (1 "mm-Einheit" würde als 1pt ≈ 0.35mm gerendert). IsFixed unterscheidet DRAWBOX (feste,
|
||||
/// nicht umbrechende Box - Inhalt, der die Höhe sprengt, wird von QuestTemplateRenderer
|
||||
/// stillschweigend am unteren Rand abgeschnitten statt umzubrechen) von FLOWDRAWBOX (fließt bei
|
||||
/// Bedarf automatisch auf weitere Seiten, siehe DrawingElementRenderer.Slice) - nur bei
|
||||
/// IsFixed=true darf/muss ein Builder seine Höhe an Height anpassen.</summary>
|
||||
public readonly record struct DeclaredDrawingBox(float Width, float Height, float MillimeterScale, bool IsFixed);
|
||||
|
||||
/// <summary>Siehe <see cref="DrawingBoxLocator"/> — dort liegt die Suche, damit auch der
|
||||
/// Vorlagen-Designer sie nutzen kann.</summary>
|
||||
public static DeclaredDrawingBox? FindDeclaredDrawingBox(LoadedTemplate template, string placeholderName) =>
|
||||
FindDeclaredDrawingBox(template.Layout, placeholderName) ??
|
||||
(template.ContinuationLayout is not null ? FindDeclaredDrawingBox(template.ContinuationLayout, placeholderName) : null);
|
||||
|
||||
private static DeclaredDrawingBox? FindDeclaredDrawingBox(TemplateLayout layout, string placeholderName)
|
||||
{
|
||||
var box = layout.Elements.Concat(layout.PageTemplates.SelectMany(p => p.Elements))
|
||||
.Concat(layout.ContentFlows.SelectMany(f => f.Elements))
|
||||
.Select(e => e switch
|
||||
{
|
||||
DrawBoxElement draw when draw.Placeholder == placeholderName => ((float Width, float Height, bool IsFixed)?)(draw.Width, draw.Height, true),
|
||||
FlowDrawBoxElement flow when flow.Placeholder == placeholderName => (flow.Width, flow.Height, false),
|
||||
_ => null,
|
||||
})
|
||||
.FirstOrDefault(b => b is not null);
|
||||
if (box is null) return null;
|
||||
var millimeterScale = UnitConverter.Points(1, "mm") / UnitConverter.Points(1, layout.Unit);
|
||||
return new DeclaredDrawingBox(box.Value.Width, box.Value.Height, millimeterScale, box.Value.IsFixed);
|
||||
}
|
||||
DrawingBoxLocator.Find(template, placeholderName);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ public class GroupMembershipTools(
|
||||
[Description("Schüler-ID.")] Guid studentId,
|
||||
[Description("Lerngruppen-ID.")] Guid groupId,
|
||||
[Description("Niveau: E, G oder Foerder. Unverändert lassen: weglassen.")] Niveau? niveau = null,
|
||||
[Description("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("Beitrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? joinedAt = null,
|
||||
[Description("Austrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? leftAt = null,
|
||||
@@ -34,6 +35,7 @@ public class GroupMembershipTools(
|
||||
|
||||
var changes = new StringBuilder();
|
||||
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 (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; }
|
||||
@@ -57,6 +59,7 @@ public class GroupMembershipTools(
|
||||
{
|
||||
Id = m.Id, StudentId = m.StudentId, GroupId = m.GroupId, AddedOn = m.AddedOn,
|
||||
Period = m.Period, JoinedAt = m.JoinedAt, LeftAt = m.LeftAt, Niveau = m.Niveau,
|
||||
IsSupportStudent = m.IsSupportStudent,
|
||||
};
|
||||
|
||||
private static string NiveauName(Niveau? n) => n switch
|
||||
|
||||
@@ -26,7 +26,7 @@ public class LetterTemplateTools(
|
||||
public List<LetterTemplateDto> ListLetterTemplates()
|
||||
{
|
||||
var result = new List<LetterTemplateDto>();
|
||||
foreach (var installed in templates.GetTemplates())
|
||||
foreach (var installed in templates.GetTemplates().Where(x => !x.IsExamCover && !x.IsStudentReport))
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
@@ -151,7 +151,7 @@ public static class StudentAttendanceCalendarDrawingBuilder
|
||||
y = gridStartY + 11 * k + 9 * k + maxWeeks * cellHeight + designTrailingGapY * k;
|
||||
|
||||
commands.Add(new DrawStringEx(0, y, 8 * k, contentWidthDesign,
|
||||
"U unentschuldigt · A abwesend · V verspätet · E entschuldigt · ! Klassenbuch",
|
||||
"U/E/A ganztägig · T teilweise · G gegangen · V verspätet · ! Klassenbuch",
|
||||
DrawingTextAlignment.AlignLeft, 6.5f * finalScale, Color: "#6B7280"));
|
||||
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 const int HotWindowDays = 14;
|
||||
private const int AbsenceReportVersion = 2;
|
||||
|
||||
/// 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".
|
||||
@@ -66,6 +67,10 @@ public sealed class UntisReportCacheService(
|
||||
DateOnly start, DateOnly end, bool forceRefresh = false, CancellationToken token = default)
|
||||
{
|
||||
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);
|
||||
|
||||
if (plan.RefreshHotWindow)
|
||||
@@ -76,7 +81,7 @@ public sealed class UntisReportCacheService(
|
||||
if (plan.FetchColdRange)
|
||||
{
|
||||
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)
|
||||
fetchState.Save(NextState(state, className, UntisCacheKind.Absences, plan));
|
||||
@@ -137,6 +142,7 @@ public sealed class UntisReportCacheService(
|
||||
Id = previous?.Id ?? Guid.NewGuid(),
|
||||
ClassName = className,
|
||||
Kind = kind,
|
||||
AbsenceReportVersion = kind == UntisCacheKind.Absences ? AbsenceReportVersion : 0,
|
||||
HotWindowFetchedAt = plan.RefreshHotWindow ? DateTime.UtcNow : previous?.HotWindowFetchedAt,
|
||||
ColdCoverageStartDate = plan.ResultingColdCoverageStartDate,
|
||||
};
|
||||
|
||||
@@ -114,6 +114,10 @@ public sealed class WebUntisIntegrationService(HttpClient http, WebUntisSettings
|
||||
x.ActivityType, x.Info, x.LessonText, x.SubstitutionText, x.StudentGroup,
|
||||
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,
|
||||
CancellationToken token = default) => ExecuteAsync(async client =>
|
||||
{
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using System.Windows.Input;
|
||||
|
||||
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
|
||||
/// 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
|
||||
/// übernimmt bewusst die frühere Sortierung aus DashboardSettingsService.DefaultCardOrder, damit
|
||||
/// sich nichts, was Nutzer bereits kennen, unvorhersehbar umsortiert.
|
||||
/// "Klausurwochen" (examload) bleibt bewusst außen vor: die Einträge dort sind Wochen-Aggregate,
|
||||
/// keine Einzelvorgänge, die sich abhaken oder anklicken lassen — sie passen nicht ins Item-Modell.</summary>
|
||||
public enum AttentionKind { MissingTeachingTime, Excuse, Correction, Unplanned, Alert, Attendance, SupportPlan }
|
||||
/// keine Einzelvorgänge, die sich abhaken oder anklicken lassen — sie passen nicht ins Item-Modell.
|
||||
/// 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",
|
||||
/// "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>
|
||||
public string ProgressLabel { get; }
|
||||
/// <summary>Färbt TrailingText wie die frühere Fehlzeiten-Warnung (fest "Foreground=Red") ein —
|
||||
/// nur bei Attendance gesetzt, weil ein AttentionItem dieser Art per Konstruktion nur entsteht,
|
||||
/// wenn die Fehlzeitenquote den Schwellenwert bereits überschreitet.</summary>
|
||||
/// bei Attendance/MissingHomework/Lateness gesetzt, weil ein AttentionItem dieser Arten per
|
||||
/// Konstruktion nur entsteht, wenn der jeweilige Schwellenwert bereits überschritten ist.</summary>
|
||||
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 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 = "",
|
||||
string dateDisplay = "", bool isOverdue = false, AlertSeverity? severity = null,
|
||||
int progressPercent = 0, string progressLabel = "", bool hasProgress = false,
|
||||
bool isWarningTrailing = false, IReadOnlyList<AttentionAction>? actions = null, Action? navigate = null)
|
||||
bool isWarningTrailing = false, bool isDefused = false,
|
||||
IReadOnlyList<AttentionAction>? actions = null, Action? navigate = null,
|
||||
Func<StudentWarningDetailViewModel>? detailFactory = null)
|
||||
{
|
||||
Kind = kind;
|
||||
Title = title;
|
||||
@@ -62,30 +87,58 @@ public sealed class AttentionItem
|
||||
ProgressLabel = progressLabel;
|
||||
HasProgress = hasProgress;
|
||||
IsWarningTrailing = isWarningTrailing;
|
||||
IsDefused = isDefused;
|
||||
Actions = actions ?? [];
|
||||
Navigate = navigate;
|
||||
_detailFactory = detailFactory;
|
||||
}
|
||||
|
||||
public bool HasSubtitle => !string.IsNullOrWhiteSpace(Subtitle);
|
||||
public bool HasTrailingText => !string.IsNullOrWhiteSpace(TrailingText);
|
||||
public bool HasDate => !string.IsNullOrWhiteSpace(DateDisplay);
|
||||
public bool HasActions => Actions.Count > 0;
|
||||
public bool HasDetail => _detailFactory is not null;
|
||||
public bool HasFooter => HasActions || HasDetail;
|
||||
public bool HasSeverity => Severity is not null;
|
||||
public bool IsHighSeverity => Severity == AlertSeverity.High;
|
||||
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
|
||||
/// die Sortierung, die ihre jeweilige LoadXxx-Methode schon immer produziert hat (z.B. Fehlzeiten
|
||||
/// nach Quote absteigend, Korrekturen nach Datum) — ein zweites, generisches "Importance"-Sortieren
|
||||
/// quer über alle Arten würde diese bewusst gewählten Reihenfolgen wieder zerstören.</summary>
|
||||
public sealed class AttentionGroup(AttentionKind kind, string header, IReadOnlyList<AttentionItem> items)
|
||||
/// quer über alle Arten würde diese bewusst gewählten Reihenfolgen wieder zerstören.
|
||||
/// 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 string Header { get; } = header;
|
||||
public IReadOnlyList<AttentionItem> Items { get; } = items;
|
||||
public AttentionKind? Kind { get; }
|
||||
public string Header { get; }
|
||||
public IReadOnlyList<AttentionItem> Items { get; }
|
||||
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
|
||||
|
||||
@@ -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 LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Desktop.ViewModels.Students;
|
||||
|
||||
@@ -26,6 +27,10 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
||||
|
||||
private string _className = "";
|
||||
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; } = [];
|
||||
|
||||
@@ -37,7 +42,8 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
||||
|
||||
public Func<List<StudentOption>, Vorgang?, Task<Vorgang?>>? OnEditVorgang { 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,
|
||||
IStudentRepository students, UntisReportCacheService cache)
|
||||
@@ -98,13 +104,16 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
||||
.Where(n => n != "");
|
||||
var item = new VorgangItem(vorgang, string.Join(", ", names), LinkDocumentation,
|
||||
UnlinkDocumentation, RemoveClassRegisterEntry, EditDocumentation)
|
||||
{ IsRevealed = revealedIds.Contains(vorgang.Id) };
|
||||
{
|
||||
IsRevealed = revealedIds.Contains(vorgang.Id),
|
||||
OnCreateFromTemplate = CreateDocumentationFromTemplate,
|
||||
};
|
||||
|
||||
var linkedIds = vorgang.DocumentationIds.ToHashSet();
|
||||
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))
|
||||
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))
|
||||
item.ClassRegisterRows.Add(new VorgangClassRegisterEntryRow(entry));
|
||||
|
||||
@@ -117,10 +126,102 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
||||
|
||||
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]
|
||||
private async Task AddVorgang()
|
||||
{
|
||||
if (OnEditVorgang is null) return;
|
||||
await EnsureFactsAsync();
|
||||
var result = await OnEditVorgang(_rosterStudentOptions, null);
|
||||
if (result is null) return;
|
||||
_vorgaenge.Save(result);
|
||||
@@ -131,6 +232,7 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
||||
private async Task EditVorgang(VorgangItem? item)
|
||||
{
|
||||
if (item is null || OnEditVorgang is null) return;
|
||||
await EnsureFactsAsync();
|
||||
var result = await OnEditVorgang(_rosterStudentOptions, item.Model);
|
||||
if (result is null) return;
|
||||
_vorgaenge.Save(result);
|
||||
@@ -160,9 +262,9 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
||||
private async Task CreateAndLinkDocumentation(VorgangItem? item)
|
||||
{
|
||||
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 result = await OnEditDocumentation(defaultStudentId, studentOptions, null);
|
||||
var result = await OnEditDocumentation(defaultStudentId, studentOptions, studentOptions, null);
|
||||
if (result is null) return;
|
||||
_documentation.Save(result);
|
||||
item.Model.DocumentationIds.Add(result.Id);
|
||||
@@ -177,19 +279,20 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
||||
private async Task EditDocumentation(DocumentationItem doc)
|
||||
{
|
||||
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;
|
||||
_documentation.Save(result);
|
||||
await LoadInternal();
|
||||
}
|
||||
|
||||
/// Dokumentation der Vorgangs-Schüler*innen, die noch nicht mit diesem Vorgang verknüpft ist —
|
||||
/// reine, ohne Repository-Zugriff testbare Filterlogik (gleiches Muster wie
|
||||
/// <see cref="ClassTeacherRosterRow.Build"/>).
|
||||
/// Dokumentation der Vorgangs-Schüler*innen (als Haupt- oder weitere Beteiligte), die noch nicht
|
||||
/// mit diesem Vorgang verknüpft ist — reine, ohne Repository-Zugriff testbare Filterlogik
|
||||
/// (gleiches Muster wie <see cref="ClassTeacherRosterRow.Build"/>).
|
||||
public static List<Documentation> FilterAvailableDocumentation(IReadOnlyList<Documentation> allDocs, Vorgang vorgang)
|
||||
{
|
||||
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)
|
||||
|
||||
@@ -66,6 +66,22 @@ public sealed record ClassAbsenceDaySummaryRow(DateOnly Date, string StudentName
|
||||
IReadOnlyList<int> PeriodNumbers, IReadOnlyList<string> Statuses, IReadOnlyList<string> AbsenceReasons,
|
||||
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 StudentDisplayName
|
||||
{
|
||||
@@ -79,11 +95,18 @@ public sealed record ClassAbsenceDaySummaryRow(DateOnly Date, string StudentName
|
||||
public string PeriodsLabel => string.Join(", ", PeriodNumbers.Order());
|
||||
public string StatusLabel => string.Join(", ", Statuses);
|
||||
public string ReasonLabel => string.Join("; ", AbsenceReasons);
|
||||
public bool IsLate => TotalAbsentPeriods == 0 || AbsenceReasons.Any(r =>
|
||||
r.Contains("verspät", StringComparison.OrdinalIgnoreCase));
|
||||
public bool IsLate => !IsEarlyDeparture && (TotalAbsentPeriods == 0 || AbsenceReasons.Any(r =>
|
||||
r.Contains("verspät", StringComparison.OrdinalIgnoreCase)));
|
||||
public bool IsUnexcused => Statuses.Any(s =>
|
||||
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")}";
|
||||
public string FriendlyStatusLabel => IsUnexcused ? "Unentschuldigt" :
|
||||
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)
|
||||
? ("E", "Entschuldigt gefehlt", "#2E7D32", ClassTeacherCalendarEventKind.Excused)
|
||||
: ("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));
|
||||
}
|
||||
|
||||
@@ -454,7 +484,7 @@ public partial class ClassTeacherDetailsViewModel : ObservableObject
|
||||
var matchedIds = rosterMatches.Select(m => m.StudentId).ToHashSet();
|
||||
return all
|
||||
.Where(d => !d.IsDeleted &&
|
||||
(matchedIds.Contains(d.StudentId) || IsUnassignedClassDocumentation(d)) &&
|
||||
(d.InvolvedStudentIds().Any(matchedIds.Contains) || IsUnassignedClassDocumentation(d)) &&
|
||||
d.Date >= start && d.Date <= end)
|
||||
.Where(d => MatchesOwnDocStudentFilter(d, rosterMatches, studentFilter))
|
||||
.OrderByDescending(d => d.IsDraft).ThenByDescending(d => d.Date)
|
||||
@@ -467,8 +497,10 @@ public partial class ClassTeacherDetailsViewModel : ObservableObject
|
||||
if (string.IsNullOrWhiteSpace(studentFilter)) return true;
|
||||
if (IsUnassignedClassDocumentation(d))
|
||||
return d.Participants.Any(p => NameContainsSearchTerm(p, studentFilter));
|
||||
var name = rosterMatches.FirstOrDefault(m => m.StudentId == d.StudentId).DisplayName;
|
||||
return name is not null && NameContainsSearchTerm(name, studentFilter);
|
||||
// Gemeinsame Einträge (weitere Beteiligte) passen, sobald eine der beteiligten Personen passt.
|
||||
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) =>
|
||||
@@ -485,8 +517,13 @@ public partial class ClassTeacherDetailsViewModel : ObservableObject
|
||||
IReadOnlyList<(Guid StudentId, string DisplayName)> rosterMatches)
|
||||
{
|
||||
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
|
||||
? $"Ohne festen Bezug · {string.Join(", ", d.Participants)}"
|
||||
: "Ohne Schülerbezug";
|
||||
|
||||
@@ -50,11 +50,7 @@ public sealed record ClassTeacherRosterRow(string StudentName, int? ExternKey, b
|
||||
{
|
||||
if (TodayAbsence is null)
|
||||
return HasRecentClassRegisterEntry ? "Neuer Klassenbucheintrag" : "Keine gemeldete Fehlzeit";
|
||||
var core = IsLate
|
||||
? $"{TodayAbsence.TotalAbsentMinutes} Min. verspätet"
|
||||
: TodayAbsence.CountsAsFullDay
|
||||
? "Ganzer Fehltag"
|
||||
: $"{TodayAbsence.TotalAbsentPeriods} Fehlstunde{(TodayAbsence.TotalAbsentPeriods == 1 ? "" : "n")}";
|
||||
var core = TodayAbsence.KindLabel;
|
||||
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
|
||||
/// sagt für Zeugnis/Attestpflicht wenig aus). <see cref="SchoolDaysElapsed"/> zählt Werktage
|
||||
/// abzüglich der über WebUntis geladenen Ferien (<see cref="ClassTeacherOverviewViewModel.CountSchoolWeekdays"/>).
|
||||
/// Zählt bewusst NUR echte Fehltage (unentschuldigt oder entschuldigt abwesend), keine reinen
|
||||
/// Verspätungstage mehr — Nutzer-Feedback: die Quote behandelte "10× 5 Min. verspätet" bisher
|
||||
/// exakt wie "10× ganztägig unentschuldigt gefehlt", obwohl beides für die eigene Reaktion
|
||||
/// (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).
|
||||
/// Zählt bewusst NUR von WebUntis als ganze Fehltage gekennzeichnete Tage. Stundenweises
|
||||
/// Fehlen bleibt davon getrennt in <see cref="YearAbsencePeriodCount"/> — auch wenn es
|
||||
/// unentschuldigt ist. Reine Verspätung landet separat in <see cref="YearLateDayCount"/>.
|
||||
public int YearAbsenceDayCount { 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
|
||||
/// in <see cref="YearAbsenceDayCount"/>/<see cref="YearAbsenceRatePercent"/>, tragen aber mit
|
||||
/// reduziertem Gewicht zu <see cref="PatternScore"/> bei.
|
||||
public int YearLateDayCount { get; init; }
|
||||
/// Entschuldigt abwesende Tage (weder unentschuldigt noch nur verspätet) — Kehrwert von
|
||||
/// <see cref="YearUnexcusedDayCount"/> innerhalb von <see cref="YearAbsenceDayCount"/>.
|
||||
/// Entschuldigte ganze Fehltage — Gegenstück zu <see cref="YearUnexcusedDayCount"/> innerhalb
|
||||
/// von <see cref="YearAbsenceDayCount"/>. Stunden stehen getrennt in den Period-Eigenschaften.
|
||||
public int YearExcusedDayCount { get; init; }
|
||||
/// Klassenbucheinträge anderer Lehrkräfte über das ganze bisherige Schuljahr mit
|
||||
/// <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.
|
||||
public DateOnly TermStart { get; init; }
|
||||
public bool HasYearSummary => SchoolDaysElapsed > 0 &&
|
||||
(YearAbsenceDayCount > 0 || YearLateDayCount > 0 || YearNegativeClassRegisterCount > 0);
|
||||
(YearAbsenceDayCount > 0 || YearAbsencePeriodCount > 0 || YearLateDayCount > 0 ||
|
||||
YearNegativeClassRegisterCount > 0);
|
||||
public int YearAbsenceRatePercent =>
|
||||
SchoolDaysElapsed <= 0 ? 0 : (int)Math.Round(100d * YearAbsenceDayCount / SchoolDaysElapsed);
|
||||
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"
|
||||
: $"{YearNegativeClassRegisterCount} negative Klassenbucheinträge seit Schuljahresbeginn";
|
||||
public string? YearSummaryTooltip => !HasYearSummary ? null :
|
||||
(YearAbsenceDayCount > 0
|
||||
? $"{YearAbsenceDayCount} von {SchoolDaysElapsed} Schultagen seit {TermStart:dd.MM.} mit Fehlzeit" +
|
||||
(YearUnexcusedDayCount > 0 ? $" · {YearUnexcusedDayCount} unentschuldigt" : "")
|
||||
: $"Keine Fehltage seit {TermStart:dd.MM.}") +
|
||||
? $"{YearAbsenceDayCount} von {SchoolDaysElapsed} Schultagen seit {TermStart:dd.MM.} als ganzer Fehltag" +
|
||||
(YearUnexcusedDayCount > 0 ? $" · davon {YearUnexcusedDayCount} unentschuldigt" : "")
|
||||
: $"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)" : "") +
|
||||
(YearNegativeClassRegisterCount > 0 ? $" · {YearNegativeClassRegisterCount} negative Klassenbucheinträge" : "") +
|
||||
(HasSuspensionEntry ? " · Suspendierung vermerkt" : "") +
|
||||
(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[] SuspensionKeywords = ["suspendier"];
|
||||
|
||||
@@ -238,8 +245,10 @@ public sealed record ClassTeacherRosterRow(string StudentName, int? ExternKey, b
|
||||
var attendanceCutoff = cutoffFor(VorgangScoreDomain.Attendance);
|
||||
var latenessCutoff = cutoffFor(VorgangScoreDomain.Lateness);
|
||||
var classbookCutoff = cutoffFor(VorgangScoreDomain.Classbook);
|
||||
var unexcused = yearEntries.Count(r => r.IsUnexcused && r.Date >= attendanceCutoff);
|
||||
var excused = yearEntries.Count(r => !r.IsUnexcused && !r.IsLate && r.Date >= attendanceCutoff);
|
||||
var unexcused = yearEntries.Where(r => r.IsUnexcused && 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 classRegister = yearRegisterEntries
|
||||
.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,
|
||||
HasClassRegisterToday = registerEntries.Any(e => TryDate(e.Date, out var date) && date == referenceDate),
|
||||
// Unentschuldigt vor Verspätet vor Entschuldigt, überschneidungsfrei — dieselbe
|
||||
// Kategorisierung wie im Wochentrend (BuildTrend). Nur Verspätung (nicht auch
|
||||
// unentschuldigt) fällt bewusst aus YearAbsenceDayCount heraus, siehe dort.
|
||||
YearAbsenceDayCount = yearEntries.Count(r => r.IsUnexcused || !r.IsLate),
|
||||
YearUnexcusedDayCount = yearEntries.Count(r => r.IsUnexcused),
|
||||
// Ganze Fehltage und stundenweises Fehlen bleiben getrennt. Insbesondere macht
|
||||
// "unentschuldigt" aus einer einzelnen Fehlstunde keinen ganzen Fehltag.
|
||||
YearAbsenceDayCount = yearEntries.Count(r => !r.IsLate && r.CountsAsFullDay),
|
||||
YearUnexcusedDayCount = yearEntries.Count(r => !r.IsLate && r.CountsAsFullDay && 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),
|
||||
YearExcusedDayCount = yearEntries.Count(r => !r.IsUnexcused && !r.IsLate),
|
||||
YearExcusedDayCount = yearEntries.Count(r => !r.IsUnexcused && !r.IsLate && r.CountsAsFullDay),
|
||||
YearNegativeClassRegisterCount = yearRegisterEntries.Count(IsNegativeClassRegisterEntry),
|
||||
HasSuspensionEntry = yearRegisterEntries.Any(e => MatchesAnyKeyword(e, SuspensionKeywords)),
|
||||
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 weekRows = rows.Where(row => row.Date >= sevenDayStart).ToList();
|
||||
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);
|
||||
|
||||
if (unexcusedDaysWeek >= 2)
|
||||
notices.Add(new ClassTeacherPatternNotice(displayName,
|
||||
$"{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)
|
||||
notices.Add(new ClassTeacherPatternNotice(displayName,
|
||||
$"{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)
|
||||
.Select(s => s!.Id)
|
||||
.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);
|
||||
OwnDocumentationCriticalCount = docs.Count(d =>
|
||||
d.Tags.Any(t => string.Equals(t, "Kritisch", StringComparison.OrdinalIgnoreCase)));
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||
|
||||
/// <summary>
|
||||
@@ -20,4 +22,21 @@ public static class UntisNameMatching
|
||||
.Where(w => w.Length > 0)
|
||||
.Select(w => w.ToLowerInvariant())
|
||||
.OrderBy(w => w, StringComparer.Ordinal));
|
||||
|
||||
/// <summary>Verwendet die Instanzen aus der Auswahlliste. Repository-Abfragen für eine Klasse
|
||||
/// liefern neue Student-Objekte mit derselben Id, die ein ComboBox.SelectedItem nicht erkennt.</summary>
|
||||
public static Dictionary<string, Student> BuildClassNameIndex(IReadOnlyList<Student> candidates,
|
||||
IEnumerable<Student> classStudents)
|
||||
{
|
||||
var classStudentIds = classStudents.Select(s => s.Id).ToHashSet();
|
||||
return BuildNameIndex(candidates.Where(s => classStudentIds.Contains(s.Id)));
|
||||
}
|
||||
|
||||
public static Dictionary<string, Student> BuildNameIndex(IEnumerable<Student> candidates) =>
|
||||
candidates
|
||||
.Select(student => (Key: NameKey(student.FullName), Student: student))
|
||||
.Where(x => x.Key.Length > 0)
|
||||
.GroupBy(x => x.Key)
|
||||
.Where(group => group.Select(x => x.Student.Id).Distinct().Count() == 1)
|
||||
.ToDictionary(group => group.Key, group => group.First().Student);
|
||||
}
|
||||
@@ -90,10 +90,26 @@ public partial class VorgangItem : ObservableObject
|
||||
_onUnlink = onUnlink;
|
||||
_onRemoveClassRegisterEntry = onRemoveClassRegisterEntry;
|
||||
_onEditDocumentation = onEditDocumentation;
|
||||
LinkedDocumentation.CollectionChanged += (_, _) => OnPropertyChanged(nameof(HasLinkedDocumentation));
|
||||
AvailableDocumentation.CollectionChanged += (_, _) => OnPropertyChanged(nameof(HasAvailableDocumentation));
|
||||
ClassRegisterRows.CollectionChanged += (_, _) => OnPropertyChanged(nameof(HasClassRegisterRows));
|
||||
}
|
||||
|
||||
[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
|
||||
/// verlassen (Nutzer-Feedback: bisher musste man dafür in den Schülerdatensatz wechseln).
|
||||
[RelayCommand]
|
||||
@@ -138,14 +154,51 @@ public partial class VorgangDialogViewModel : ObservableObject
|
||||
[ObservableProperty] private string _titleError = "";
|
||||
[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 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;
|
||||
_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 =>
|
||||
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;
|
||||
|
||||
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); }
|
||||
|
||||
/// 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]
|
||||
private void Save()
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
|
||||
@@ -26,6 +27,8 @@ public partial class DashboardViewModel : ObservableObject
|
||||
private readonly IParticipationRepository _participationEntries;
|
||||
private readonly IStudentRepository _students;
|
||||
private readonly IDocumentationRepository _documentation;
|
||||
private readonly IVorgangRepository _vorgaenge;
|
||||
private readonly IDashboardWarningSnoozeRepository _warningSnoozes;
|
||||
private readonly ITimetableSlotRepository _timetableSlots;
|
||||
private readonly PeriodScheduleService _periodSchedule;
|
||||
private readonly AttendanceBalanceService _attendanceBalance;
|
||||
@@ -40,6 +43,7 @@ public partial class DashboardViewModel : ObservableObject
|
||||
private readonly SchoolWeatherService? _schoolWeather;
|
||||
private readonly UntisHubService _untisHub;
|
||||
private readonly WebUntisIntegrationService _webUntis;
|
||||
private readonly StudentWarningEvidenceService _evidence;
|
||||
private readonly Func<DateTime> _now;
|
||||
|
||||
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
|
||||
/// Stichprobe. Dieselbe Konstante wie GroupOverviewViewModel.AttendanceMinSampleSize.
|
||||
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
|
||||
/// 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
|
||||
@@ -107,6 +129,8 @@ public partial class DashboardViewModel : ObservableObject
|
||||
|
||||
private readonly List<OpenExcuseItem> _excuses = [];
|
||||
private readonly List<AttentionItem> _attendanceItems = [];
|
||||
private readonly List<AttentionItem> _missingHomeworkItems = [];
|
||||
private readonly List<AttentionItem> _latenessItems = [];
|
||||
private readonly List<AttentionItem> _supportItems = [];
|
||||
private readonly List<AttentionItem> _correctionItems = [];
|
||||
private readonly List<AttentionItem> _unplannedItems = [];
|
||||
@@ -119,10 +143,13 @@ public partial class DashboardViewModel : ObservableObject
|
||||
private static readonly (AttentionKind Kind, string Header)[] AttentionGroupOrder =
|
||||
[
|
||||
(AttentionKind.MissingTeachingTime, "Unterrichtszeit nacherfassen"),
|
||||
// Die Fehlzeitenquote ist auch in fremden Klassen unmittelbar relevant, waehrend offene
|
||||
// Entschuldigungen nur fuer die eigene Klasse bearbeitet werden koennen. Deshalb steht sie
|
||||
// im Dashboard vor den Entschuldigungen statt weiter unten zwischen den sonstigen Hinweisen.
|
||||
// Die Fehlzeitenquote, Hausaufgaben- und Verspätungs-Warnungen sind auch in fremden Klassen
|
||||
// unmittelbar relevant, waehrend offene Entschuldigungen nur fuer die eigene Klasse bearbeitet
|
||||
// werden koennen. Deshalb stehen alle drei im Dashboard vor den Entschuldigungen statt weiter
|
||||
// unten zwischen den sonstigen Hinweisen.
|
||||
(AttentionKind.Attendance, "Fehlzeiten-Warnung"),
|
||||
(AttentionKind.Lateness, "Verspätungen-Warnung"),
|
||||
(AttentionKind.MissingHomework, "Hausaufgaben-Warnung"),
|
||||
(AttentionKind.Excuse, "Offene Entschuldigungen"),
|
||||
(AttentionKind.Correction, "Offene Korrekturen"),
|
||||
(AttentionKind.Unplanned, "Ungeplante Stunden"),
|
||||
@@ -133,6 +160,14 @@ public partial class DashboardViewModel : ObservableObject
|
||||
// Navigation-Callback – wird von App.axaml.cs verdrahtet
|
||||
public Action<Guid>? OnNavigateToGroup { 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
|
||||
// OnNavigateToGroup (Lerngruppen-Kacheln, Tab "Übersicht"), da der Sprung von einer konkreten
|
||||
// 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 OpenTaskCount => OpenTasks.Count;
|
||||
public int UpcomingCount => UpcomingDates.Count;
|
||||
public int AttentionCount => _excuses.Count + _attendanceItems.Count + _supportItems.Count
|
||||
+ _correctionItems.Count + _unplannedItems.Count + _alertItems.Count + _missingTimeItems.Count;
|
||||
/// Zurückgestellte/entschärfte Warnungen zählen bewusst nicht mit (Nutzer-Feedback) — sie stehen
|
||||
/// 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 OpenTaskSummary => OpenTaskCount == 1 ? "1 Aufgabe" : $"{OpenTaskCount} Aufgaben";
|
||||
public string AttentionSummary => AttentionCount == 1 ? "1 offener Punkt" : $"{AttentionCount} offene Punkte";
|
||||
@@ -175,7 +218,8 @@ public partial class DashboardViewModel : ObservableObject
|
||||
IReportGradeRepository reportGrades, IGroupMembershipRepository memberships,
|
||||
IWorkTaskRepository tasks, IParticipationSessionRepository participationSessions,
|
||||
IParticipationRepository participationEntries, IStudentRepository students,
|
||||
IDocumentationRepository documentation, ITimetableSlotRepository timetableSlots,
|
||||
IDocumentationRepository documentation, IVorgangRepository vorgaenge,
|
||||
IDashboardWarningSnoozeRepository warningSnoozes, ITimetableSlotRepository timetableSlots,
|
||||
PeriodScheduleService periodSchedule, AttendanceBalanceService attendanceBalance, SchoolYearService sy,
|
||||
DashboardSettingsService dashboardSettings, ISchoolHolidayRepository schoolHolidays,
|
||||
PublicHolidayService publicHolidays, SchoolCalendarSettingsService calendarSettings,
|
||||
@@ -189,6 +233,7 @@ public partial class DashboardViewModel : ObservableObject
|
||||
_examResults = examResults; _grades = grades; _reportGrades = reportGrades; _memberships = memberships;
|
||||
_participationSessions = participationSessions; _participationEntries = participationEntries;
|
||||
_students = students; _documentation = documentation;
|
||||
_vorgaenge = vorgaenge; _warningSnoozes = warningSnoozes;
|
||||
_timetableSlots = timetableSlots; _periodSchedule = periodSchedule;
|
||||
_attendanceBalance = attendanceBalance; _sy = sy; _dashboardSettings = dashboardSettings;
|
||||
_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
|
||||
// zufaellig rot oder gruen (siehe TODO.md, Abschnitt 9, Nachtrag Uhrzeit-Wraparound).
|
||||
_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)
|
||||
{
|
||||
annualPlanSync.DataChanged += () => Avalonia.Threading.Dispatcher.UIThread.Post(LoadCalendar);
|
||||
@@ -286,6 +336,8 @@ public partial class DashboardViewModel : ObservableObject
|
||||
LoadCalendar();
|
||||
LoadOpenExcuses(groups.Values.ToList(), today);
|
||||
LoadAttendanceWarnings(today);
|
||||
LoadMissingHomeworkWarnings(today);
|
||||
LoadLatenessWarnings(today);
|
||||
LoadExamWeekLoads(groups, today);
|
||||
LoadMissingTeachingTime(today);
|
||||
LoadSupportPlanReviews(today);
|
||||
@@ -305,7 +357,9 @@ public partial class DashboardViewModel : ObservableObject
|
||||
UpcomingCard.IsEmpty = UpcomingDates.Count == 0;
|
||||
ExamLoadCard.IsEmpty = ExamWeekLoads.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
|
||||
// ueber EffectiveIsVisible daran, und davon wiederum die Zeilen-/Spaltenzuordnung.
|
||||
@@ -374,16 +428,95 @@ public partial class DashboardViewModel : ObservableObject
|
||||
|
||||
// ── 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)
|
||||
{
|
||||
_attendanceItems.Clear();
|
||||
var schoolYear = _sy.CurrentSchoolYear();
|
||||
var from = _sy.SchoolYearStart(schoolYear);
|
||||
var to = _sy.SchoolYearEnd(schoolYear);
|
||||
|
||||
// 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).
|
||||
var sessionDates = _participationSessions.GetAll().ToDictionary(s => s.Id, s => s.Date);
|
||||
var sessionDates = BuildSessionDateLookup();
|
||||
var recentVorgaenge = BuildRecentVorgangTagSet();
|
||||
var activeSnoozes = BuildActiveSnoozeSet(today);
|
||||
|
||||
var items = new List<AttendanceWarningItem>();
|
||||
foreach (var student in _students.GetAll())
|
||||
@@ -398,13 +531,93 @@ public partial class DashboardViewModel : ObservableObject
|
||||
if (balance.TotalChecked >= AttendanceMinSampleSize && balance.ExceedsThreshold)
|
||||
items.Add(new AttendanceWarningItem(student.Id, student.FullName, balance.AbsenceRatePercent));
|
||||
}
|
||||
foreach (var item in items.OrderByDescending(i => i.AbsenceRatePercent))
|
||||
_attendanceItems.Add(ToAttentionItem(item));
|
||||
var ordered = items
|
||||
.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.#} %",
|
||||
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) ───────────────────────────────────────
|
||||
//
|
||||
@@ -757,19 +970,33 @@ public partial class DashboardViewModel : ObservableObject
|
||||
[AttentionKind.Unplanned] = _unplannedItems,
|
||||
[AttentionKind.Alert] = _alertItems,
|
||||
[AttentionKind.Attendance] = _attendanceItems,
|
||||
[AttentionKind.MissingHomework] = _missingHomeworkItems,
|
||||
[AttentionKind.Lateness] = _latenessItems,
|
||||
[AttentionKind.SupportPlan] = _supportItems,
|
||||
};
|
||||
|
||||
Attention.Clear();
|
||||
var deferred = new List<AttentionItem>();
|
||||
foreach (var (kind, header) in AttentionGroupOrder)
|
||||
{
|
||||
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;
|
||||
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(
|
||||
AttentionKind.Excuse, e.StudentName, subtitle: $"{e.GroupName} · {e.DateDisplay}",
|
||||
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 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 int ExamCount { get; } = examCount;
|
||||
|
||||
@@ -42,6 +42,8 @@ public partial class ExamsOverviewViewModel : ObservableObject
|
||||
|
||||
public Func<Exam, Task>? OnGradeExam { 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? OnNavigateToGroups { get; set; }
|
||||
public bool HasNoExams => Rows.Count == 0;
|
||||
@@ -169,6 +171,20 @@ public partial class ExamsOverviewViewModel : ObservableObject
|
||||
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]
|
||||
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 Exam _exam;
|
||||
private readonly GradingSystem _gradingSystem;
|
||||
private readonly IStudentRepository? _students;
|
||||
private readonly double _examMaxPoints;
|
||||
private List<ExamResult> _gradedResults = [];
|
||||
|
||||
@@ -38,19 +39,69 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
|
||||
public ObservableCollection<GradeBarItem> GradeDistribution { 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 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;
|
||||
_gradingSystem = gradingSystem;
|
||||
_examMaxPoints = exam.Tasks.Sum(t => t.MaxPoints);
|
||||
_gradingSystem = gradingSystem; _students = students;
|
||||
_examMaxPoints = ExamScoringService.Maximum(exam.Tasks, ExamVariant.A);
|
||||
|
||||
foreach (var e in exam.GradingKey.OrderByDescending(e => e.MinPercent))
|
||||
AddGradingKeyRowInternal(e.Grade, e.MinPercent);
|
||||
|
||||
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()
|
||||
@@ -98,6 +149,9 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
foreach (var e in GradingKeyEntries)
|
||||
e.AbsolutePointsDisplay = _examMaxPoints <= 0
|
||||
? "–"
|
||||
: _exam.Tasks.Any(t => t.Variant is not null)
|
||||
? $"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";
|
||||
}
|
||||
@@ -116,6 +170,12 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
GradingKeyValidation = "";
|
||||
_exam.GradingKey = key;
|
||||
_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.";
|
||||
}
|
||||
|
||||
@@ -127,7 +187,8 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
GradingKeyValidation = _grading.ValidateGradingKey(currentKey) ?? "";
|
||||
|
||||
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();
|
||||
|
||||
GradeDistribution.Clear();
|
||||
@@ -171,14 +232,17 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
{
|
||||
TaskAnalysis.Clear();
|
||||
var tasks = _exam.Tasks.OrderBy(t => t.Nr).ToList();
|
||||
var labels = ExamScoringService.TaskLabels(tasks);
|
||||
for (var i = 0; i < tasks.Count; 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
|
||||
? 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(BelowThresholdLabel2)) csv.AddRow(BelowThresholdLabel2, BelowThresholdDisplay2);
|
||||
csv.AddRow("Bewertet", GradedCount)
|
||||
.AddRow("Abwesend", AbsentCount)
|
||||
.AddBlankRow()
|
||||
.AddRow("Abwesend", AbsentCount);
|
||||
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("Aufgabe", "Ø Erfüllungsgrad", "Auffällig schwach");
|
||||
foreach (var t in TaskAnalysis)
|
||||
@@ -221,6 +292,9 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
|
||||
// ── Notenspiegel-Balken ────────────────────────────────────────────────────
|
||||
|
||||
public record RepeatComparisonItem(string StudentName, string OriginalGrade,
|
||||
string RepeatGrade, string EffectiveGrade);
|
||||
|
||||
public class GradeBarItem
|
||||
{
|
||||
public string Grade { get; }
|
||||
@@ -248,9 +322,9 @@ public class TaskAnalysisItem
|
||||
public bool IsWeak { 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;
|
||||
AvgPercentDisplay = $"{avgPercent.ToString("0.#", CultureInfo.InvariantCulture)} %";
|
||||
IsWeak = avgPercent < 50.0;
|
||||
|
||||
@@ -10,48 +10,126 @@ namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||
|
||||
// ── 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
|
||||
{
|
||||
private readonly IExamResultRepository _results;
|
||||
private readonly GradingService _grading;
|
||||
private readonly Exam _exam;
|
||||
private readonly double _examMaxPoints;
|
||||
private readonly ExamGradingSettingsService? _settings;
|
||||
|
||||
public string ExamTitle => _exam.Title;
|
||||
public string ExamDateLabel => _exam.Date.ToString("dd.MM.yyyy");
|
||||
public string NiveauLabel => _exam.Niveau.HasValue ? NiveauDisplay.ToName(_exam.Niveau) : "";
|
||||
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 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,
|
||||
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();
|
||||
_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 membershipList = memberships.GetByGroup(groupId);
|
||||
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))
|
||||
{
|
||||
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);
|
||||
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.HasStoredResult = result is not null;
|
||||
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
|
||||
/// sonst dauerhaft den live abgeleiteten Korrekturstatus (ExamPriorityService), weil niemand
|
||||
@@ -72,6 +150,7 @@ public partial class ExamResultRow : ObservableObject
|
||||
private readonly Guid _resultId;
|
||||
private readonly List<GradingKeyEntry> _gradingKey;
|
||||
private readonly double _examMaxPoints;
|
||||
private readonly List<ExamTask> _tasks;
|
||||
private readonly GradingService _grading;
|
||||
|
||||
public Guid StudentId { get; }
|
||||
@@ -83,24 +162,37 @@ public partial class ExamResultRow : ObservableObject
|
||||
[ObservableProperty] private string _comment = "";
|
||||
[ObservableProperty] private double _totalPoints;
|
||||
[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 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,
|
||||
List<GradingKeyEntry> gradingKey, double examMaxPoints, GradingService grading)
|
||||
{
|
||||
StudentId = studentId; Name = name;
|
||||
_gradingKey = gradingKey; _examMaxPoints = examMaxPoints; _grading = grading;
|
||||
_gradingKey = gradingKey; _examMaxPoints = examMaxPoints; _grading = grading; _tasks = tasks;
|
||||
_resultId = existing?.Id ?? Guid.NewGuid();
|
||||
_absent = existing?.Absent ?? false;
|
||||
_comment = existing?.Comment ?? "";
|
||||
_variantName = existing?.Variant.ToString() ?? "A";
|
||||
|
||||
for (var i = 0; i < tasks.Count; i++)
|
||||
{
|
||||
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); };
|
||||
Cells.Add(cell);
|
||||
}
|
||||
@@ -114,12 +206,20 @@ public partial class ExamResultRow : ObservableObject
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
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));
|
||||
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()
|
||||
@@ -127,10 +227,11 @@ public partial class ExamResultRow : ObservableObject
|
||||
Id = _resultId,
|
||||
ExamId = examId,
|
||||
StudentId = StudentId,
|
||||
Points = Cells.Select(c => c.Value ?? 0).ToList(),
|
||||
Points = HasPoints ? Cells.Select(c => c.Value ?? 0).ToList() : [],
|
||||
TotalPoints = TotalPoints,
|
||||
Grade = Absent ? null : GradeDisplay,
|
||||
Grade = Absent || !HasPoints ? null : GradeDisplay,
|
||||
Absent = Absent,
|
||||
Variant = Variant,
|
||||
Comment = string.IsNullOrWhiteSpace(Comment) ? null : Comment.Trim(),
|
||||
};
|
||||
}
|
||||
@@ -142,6 +243,7 @@ public partial class PointsCell : ObservableObject
|
||||
public double MaxPoints { get; }
|
||||
[ObservableProperty] private double? _value;
|
||||
[ObservableProperty] private bool _isInvalid;
|
||||
[ObservableProperty] private bool _isApplicable = true;
|
||||
|
||||
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,
|
||||
/// 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)
|
||||
{
|
||||
var changed = Value != value;
|
||||
Value = value;
|
||||
IsInvalid = IsOutOfRange(value);
|
||||
if (!IsInvalid) OnChanged?.Invoke();
|
||||
if (!IsInvalid && changed) OnChanged?.Invoke();
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
private readonly IExamRepository _exams;
|
||||
private readonly IExamResultRepository? _results;
|
||||
private readonly ICompetencyDomainRepository _competencyDomains;
|
||||
private readonly IGradingKeyTemplateRepository _gradingKeyTemplates;
|
||||
private readonly GradingService _grading;
|
||||
@@ -41,20 +42,52 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
[ObservableProperty] private string _newTemplateName = "";
|
||||
[ObservableProperty] private string _gradingKeyValidation = "";
|
||||
[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 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 string TotalPointsDisplay =>
|
||||
$"{TotalPoints.ToString("0.##", CultureInfo.InvariantCulture)} Punkte gesamt";
|
||||
public string TotalPointsDisplay => Tasks.Any(t => t.VariantName != "Beide")
|
||||
? $"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<GradingKeyEntryEditItem> GradingKeyEntries { get; } = [];
|
||||
public ObservableCollection<GradingKeyTemplate> AvailableTemplates { get; } = [];
|
||||
|
||||
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";
|
||||
|
||||
/// 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,
|
||||
Guid groupId, Guid? subjectId, int gradeLevel, GradingSystem gradingSystem,
|
||||
string defaultSubjectName, bool isDifferentiated, Exam? editingExam, Exam? duplicateSource,
|
||||
Guid competencyCatalogVersionId = default)
|
||||
Guid competencyCatalogVersionId = default, IExamResultRepository? results = null)
|
||||
{
|
||||
_exams = exams; _competencyDomains = competencyDomains;
|
||||
_results = results;
|
||||
_gradingKeyTemplates = gradingKeyTemplates; _grading = grading;
|
||||
_groupId = groupId; _subjectId = subjectId; _gradeLevel = gradeLevel;
|
||||
_competencyCatalogVersionId = competencyCatalogVersionId;
|
||||
@@ -76,6 +110,13 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
_duplicateSource = duplicateSource;
|
||||
_subjectName = defaultSubjectName;
|
||||
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
|
||||
&& _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
|
||||
// gerade eine andere Niveau-Variante (E/G/Förder) derselben Klausur anzulegen.
|
||||
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))
|
||||
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);
|
||||
foreach (var e in source.GradingKey.OrderByDescending(e => e.MinPercent))
|
||||
AddGradingKeyRowInternal(e.Grade, e.MinPercent);
|
||||
@@ -113,12 +168,44 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
foreach (var t in Tasks) t.ShowWeight = UseWeighting;
|
||||
RecomputeTotals();
|
||||
UpdateWeekLoadHint();
|
||||
_initializing = false;
|
||||
}
|
||||
|
||||
partial void OnUseWeightingChanged(bool 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();
|
||||
|
||||
@@ -127,7 +214,8 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
/// ExamWeekLoadService), hier geht es um die eigene Häufung über alle Kurse hinweg.
|
||||
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 = "";
|
||||
return;
|
||||
@@ -148,11 +236,14 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
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,
|
||||
BuildCompetencyTagGroups(competencies))
|
||||
{
|
||||
VariantName = variant?.ToString() ?? "Beide",
|
||||
IsBonus = isBonus,
|
||||
OnChanged = RecomputeTotals,
|
||||
OnRemove = RemoveTask,
|
||||
OnMoveUp = MoveTaskUp,
|
||||
@@ -197,11 +288,14 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
private void RenumberTasks()
|
||||
{
|
||||
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()
|
||||
{
|
||||
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(TotalPointsDisplay));
|
||||
RecomputeGradingKeyAbsolutes();
|
||||
@@ -214,6 +308,9 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
foreach (var e in GradingKeyEntries)
|
||||
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)} " +
|
||||
$"von {TotalPoints.ToString("0.##", CultureInfo.InvariantCulture)} Punkten";
|
||||
}
|
||||
@@ -288,6 +385,7 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
private void Save()
|
||||
{
|
||||
TitleError = ""; DateTextError = ""; ReturnedAtTextError = ""; GradingKeyValidation = "";
|
||||
RepeatError = ""; TaskPointsError = "";
|
||||
var valid = true;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(Title)) { TitleError = "Titel erforderlich."; valid = false; }
|
||||
@@ -313,6 +411,32 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
var gradingKey = BuildGradingKeyEntries();
|
||||
var gradingKeyError = _grading.ValidateGradingKey(gradingKey);
|
||||
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;
|
||||
|
||||
@@ -325,12 +449,34 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
Result.Niveau = NiveauDisplay.FromName(SelectedNiveauName);
|
||||
Result.Tasks = Tasks.Select(t => t.ToModel()).ToList();
|
||||
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
|
||||
// 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.
|
||||
if (_duplicateSource is not null)
|
||||
Result.SharedExamGroupId = _duplicateSource.SharedExamGroupId ?? _duplicateSource.Id;
|
||||
_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
|
||||
{
|
||||
[ObservableProperty] private int _nr;
|
||||
/// Angezeigte Nummer — Bonusaufgaben zählen nicht mit (siehe ExamScoringService.TaskNumbers).
|
||||
[ObservableProperty] private string _displayNr = "";
|
||||
[ObservableProperty] private string _title = "";
|
||||
[ObservableProperty] private double _maxPoints;
|
||||
[ObservableProperty] private double _weight = 1.0;
|
||||
[ObservableProperty] private bool _isCompetencyPanelOpen;
|
||||
[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 ObservableCollection<CompetencyTagGroup> CompetencyTagGroups { get; } = [];
|
||||
@@ -409,6 +560,8 @@ public partial class ExamTaskEditItem : ObservableObject
|
||||
[RelayCommand] private void MoveDown() => OnMoveDown?.Invoke(this);
|
||||
|
||||
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()
|
||||
{
|
||||
@@ -416,6 +569,8 @@ public partial class ExamTaskEditItem : ObservableObject
|
||||
Title = string.IsNullOrWhiteSpace(Title) ? null : Title.Trim(),
|
||||
MaxPoints = MaxPoints,
|
||||
Weight = Weight,
|
||||
Variant = VariantName switch { "A" => ExamVariant.A, "B" => ExamVariant.B, _ => null },
|
||||
IsBonus = IsBonus,
|
||||
Competencies = Competencies,
|
||||
};
|
||||
}
|
||||
@@ -54,12 +54,16 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
||||
public Func<GradeOverviewRow, Task>? OnManageStudentGrades { get; set; }
|
||||
public Func<Task>? OnCollectiveGrade { get; set; }
|
||||
public Func<Task>? OnReportGrades { get; set; }
|
||||
public Func<Guid?, Task>? OnInterimGrades { get; set; }
|
||||
public Func<GradeOverviewRow, Task>? OnShowPerformanceOverview { get; set; }
|
||||
|
||||
private readonly IInterimGradeRepository _interimGrades;
|
||||
|
||||
public GradeOverviewTabViewModel(IGradeRepository grades, IExamRepository exams,
|
||||
IExamResultRepository results, IStudentRepository students,
|
||||
IGroupMembershipRepository memberships, GradingService grading)
|
||||
IGroupMembershipRepository memberships, IInterimGradeRepository interimGrades, GradingService grading)
|
||||
{
|
||||
_interimGrades = interimGrades;
|
||||
_grades = grades; _exams = exams; _results = results;
|
||||
_students = students; _memberships = memberships; _grading = grading;
|
||||
_selectedPeriod = PeriodOptions[0];
|
||||
@@ -131,6 +135,15 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
||||
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()
|
||||
{
|
||||
var period = SelectedPeriod.Period;
|
||||
@@ -170,6 +183,15 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
||||
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();
|
||||
foreach (var student in students)
|
||||
{
|
||||
@@ -178,6 +200,7 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
||||
|
||||
var cells = new List<string>();
|
||||
var numeric = new List<(string Grade, double Weight)>();
|
||||
var examEntries = new List<(Exam Exam, string Grade)>();
|
||||
|
||||
foreach (var exam in exams)
|
||||
{
|
||||
@@ -189,8 +212,10 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
||||
if (result.Absent) { cells.Add("abwesend"); continue; }
|
||||
var display = FormatValue(result.Grade);
|
||||
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)
|
||||
{
|
||||
@@ -204,6 +229,10 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
||||
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 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;
|
||||
/// 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)
|
||||
|
||||
@@ -206,11 +206,15 @@ public partial class GroupOverviewViewModel : ObservableObject
|
||||
|
||||
private (double Average, int Count)? ComputeExamAverage(Guid groupId)
|
||||
{
|
||||
var system = _groups.GetById(groupId)?.GradingSystem ?? GradingSystem.Grades1To6;
|
||||
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))
|
||||
.Select(r => (Grade: r.Grade!, Weight: 1.0))
|
||||
.ToList();
|
||||
.Select(r => (r.StudentId, Exam: e, Grade: r.Grade!)))
|
||||
.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);
|
||||
}
|
||||
|
||||
@@ -292,6 +296,7 @@ public partial class GroupOverviewViewModel : ObservableObject
|
||||
{
|
||||
DraftDocumentationCount = _students.GetByGroup(_groupId)
|
||||
.SelectMany(s => _documentation.GetByStudent(s.Id))
|
||||
.DistinctBy(d => d.Id)
|
||||
.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
|
||||
// kurzzeitig null — ein verschachtelter Pfad würde dafür jedes Mal einen Binding-Fehler loggen.
|
||||
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 IsEditable => Group is { IsActive: true };
|
||||
public string SubjectName { get; private set; } = "";
|
||||
@@ -205,6 +207,7 @@ public partial class GroupDetailViewModel : ObservableObject
|
||||
partial void OnGroupChanged(LearningGroup? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsDifferentiated));
|
||||
OnPropertyChanged(nameof(ShowSupportColumn));
|
||||
OnPropertyChanged(nameof(IsReadOnly));
|
||||
OnPropertyChanged(nameof(IsEditable));
|
||||
NotifyWriteCommands();
|
||||
@@ -234,6 +237,8 @@ public partial class GroupDetailViewModel : ObservableObject
|
||||
public Func<ExamSummary, Task<bool>>? OnConfirmDeleteExam { get; set; }
|
||||
public Func<Exam, Task>? OnGradeExam { 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 GroupDetailViewModel(IGroupRepository groups, IStudentRepository students,
|
||||
@@ -322,6 +327,7 @@ public partial class GroupDetailViewModel : ObservableObject
|
||||
var membership = _memberships.GetByStudentAndGroup(summary.Id, Group.Id);
|
||||
if (membership is null) return;
|
||||
membership.Niveau = summary.Niveau;
|
||||
membership.IsSupportStudent = summary.IsSupportStudent;
|
||||
_memberships.Save(membership);
|
||||
}
|
||||
|
||||
@@ -411,6 +417,24 @@ public partial class GroupDetailViewModel : ObservableObject
|
||||
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))]
|
||||
private async Task DuplicateExam()
|
||||
{
|
||||
@@ -427,6 +451,11 @@ public partial class GroupDetailViewModel : ObservableObject
|
||||
if (SelectedExam is null || OnConfirmDeleteExam is null) return;
|
||||
var selected = SelectedExam;
|
||||
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);
|
||||
SelectedExam = null;
|
||||
ReloadExams();
|
||||
@@ -480,6 +509,8 @@ public partial class GroupDetailViewModel : ObservableObject
|
||||
EditExamCommand.NotifyCanExecuteChanged();
|
||||
GradeExamCommand.NotifyCanExecuteChanged();
|
||||
EvaluateExamCommand.NotifyCanExecuteChanged();
|
||||
RevealExamCommand.NotifyCanExecuteChanged();
|
||||
ExamCoverSheetsCommand.NotifyCanExecuteChanged();
|
||||
DuplicateExamCommand.NotifyCanExecuteChanged();
|
||||
DeleteExamCommand.NotifyCanExecuteChanged();
|
||||
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
|
||||
@@ -509,6 +540,8 @@ public partial class GroupDetailViewModel : ObservableObject
|
||||
EditExamCommand.NotifyCanExecuteChanged();
|
||||
GradeExamCommand.NotifyCanExecuteChanged();
|
||||
EvaluateExamCommand.NotifyCanExecuteChanged();
|
||||
RevealExamCommand.NotifyCanExecuteChanged();
|
||||
ExamCoverSheetsCommand.NotifyCanExecuteChanged();
|
||||
DuplicateExamCommand.NotifyCanExecuteChanged();
|
||||
DeleteExamCommand.NotifyCanExecuteChanged();
|
||||
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
|
||||
@@ -558,6 +591,7 @@ public partial class StudentSummary : ObservableObject
|
||||
public string AvatarTooltip { get; }
|
||||
|
||||
[ObservableProperty] private Niveau? _niveau;
|
||||
[ObservableProperty] private bool _isSupportStudent;
|
||||
|
||||
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}"
|
||||
: "Aktiv";
|
||||
_niveau = membership?.Niveau;
|
||||
_isSupportStudent = membership?.IsSupportStudent ?? false;
|
||||
}
|
||||
|
||||
partial void OnIsSupportStudentChanged(bool value) => OnChanged?.Invoke(this);
|
||||
|
||||
partial void OnNiveauChanged(Niveau? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(NiveauName));
|
||||
@@ -618,12 +655,23 @@ public class ExamSummary
|
||||
public string StatusColorHex { get; }
|
||||
public string ReturnedAtDisplay { get; }
|
||||
public string NiveauLabel { get; }
|
||||
public string TypeLabel { get; }
|
||||
|
||||
public ExamSummary(Core.Models.Exam e)
|
||||
{
|
||||
Id = e.Id; Title = e.Title; Date = e.Date.ToString("dd.MM.yyyy"); Status = e.Status;
|
||||
ReturnedAtDisplay = e.ReturnedAt?.ToString("dd.MM.yyyy") ?? "";
|
||||
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
|
||||
{
|
||||
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
|
||||
{
|
||||
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 IExamRepository _exams;
|
||||
private readonly IExamResultRepository _results;
|
||||
private readonly IGradeRepository _grades;
|
||||
private readonly IUnitRepository _units;
|
||||
private readonly Dictionary<Guid, GroupMembership> _membershipsByStudent;
|
||||
@@ -28,12 +24,8 @@ public partial class ParticipationWizardDialogViewModel : ObservableObject
|
||||
private readonly GradingSystem _gradingSystem;
|
||||
|
||||
private readonly List<Student> _students;
|
||||
private readonly List<ParticipationSession> _allSessions;
|
||||
private readonly List<ParticipationSection> _sectionList;
|
||||
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;
|
||||
private readonly ParticipationTimelineBuilder _timeline;
|
||||
|
||||
public string GroupLabel { get; }
|
||||
|
||||
@@ -79,22 +71,19 @@ public partial class ParticipationWizardDialogViewModel : ObservableObject
|
||||
IGradeRepository grades, IUnitRepository units, GradingService grading,
|
||||
Guid groupId, string schoolYear, GradingSystem gradingSystem, string groupLabel)
|
||||
{
|
||||
_sessions = sessions; _entries = entries; _sectionRepo = sectionRepo;
|
||||
_exams = exams; _results = results; _grades = grades; _units = units; _grading = grading;
|
||||
_sectionRepo = sectionRepo;
|
||||
_grades = grades; _units = units; _grading = grading;
|
||||
_groupId = groupId; _schoolYear = schoolYear; _gradingSystem = gradingSystem;
|
||||
GroupLabel = groupLabel;
|
||||
_membershipsByStudent = memberships.GetByGroup(groupId).ToDictionary(m => m.StudentId);
|
||||
|
||||
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);
|
||||
_timeline = new ParticipationTimelineBuilder(sessions, entries, aspects, exams, results, grades,
|
||||
_membershipsByStudent, grading, groupId, gradingSystem);
|
||||
var schoolYearRange = GroupMembershipService.SchoolYearPeriod(schoolYear, SchoolYearPeriodKind.FullYear);
|
||||
_students = students.GetByGroup(groupId)
|
||||
.Where(s => !_membershipsByStudent.TryGetValue(s.Id, out var membership)
|
||||
|| GroupMembershipService.Overlaps(membership, schoolYearRange.From, schoolYearRange.To))
|
||||
.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();
|
||||
|
||||
_rollupPeriod = RollupPeriodOptions[0];
|
||||
@@ -131,153 +120,28 @@ public partial class ParticipationWizardDialogViewModel : ObservableObject
|
||||
|
||||
private void BuildTimeline(Guid studentId)
|
||||
{
|
||||
var points = new List<(DateOnly Date, WizardTimelinePoint Point)>();
|
||||
|
||||
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();
|
||||
var points = _timeline.BuildPoints(studentId);
|
||||
|
||||
Timeline.Clear();
|
||||
foreach (var section in _sectionList)
|
||||
{
|
||||
var group = new WizardSectionGroup($"{section.Label}\n{section.StartDate:dd.MM.}–{section.EndDate:dd.MM.}", isOpen: false);
|
||||
foreach (var (date, point) in points.Where(p => p.Date >= section.StartDate && p.Date <= section.EndDate))
|
||||
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);
|
||||
Timeline.Add(group);
|
||||
}
|
||||
|
||||
var openStart = ComputeOpenStart();
|
||||
var openGroup = new WizardSectionGroup($"läuft seit {openStart:dd.MM.}", isOpen: true);
|
||||
foreach (var (date, point) in points.Where(p => p.Date >= openStart))
|
||||
var openGroup = new WizardSectionGroup(ParticipationTimelineBuilder.OpenBandLabel(openStart), isOpen: true);
|
||||
foreach (var point in points.Where(p => p.Date >= openStart))
|
||||
openGroup.Points.Add(point);
|
||||
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 ────────────────────────────────────────────────────────────
|
||||
|
||||
private DateOnly ComputeOpenStart() =>
|
||||
_sectionList.Count > 0 ? _sectionList.Max(s => s.EndDate).AddDays(1)
|
||||
: (_allSessions.Count > 0 ? _allSessions.Min(s => s.Date) : DateOnly.FromDateTime(DateTime.Today));
|
||||
_timeline.OpenStart(_sectionList, DateOnly.FromDateTime(DateTime.Today));
|
||||
|
||||
/// Schlägt als Abschnittsende bewusst nicht immer "heute" vor: Wenn seit Abschnittsbeginn
|
||||
/// 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 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),
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
var suggestion = ComputeSuggestion(student.Id, start, end);
|
||||
var suggestion = _timeline.ComputeSuggestion(student.Id, start, end);
|
||||
if (suggestion is null) continue;
|
||||
_grades.Save(new Grade
|
||||
{
|
||||
|
||||
@@ -33,7 +33,7 @@ public partial class PersonalizeWorksheetDialogViewModel : ObservableObject
|
||||
IStudentRepository students, WorksheetTemplateStore templates, ITemplateRenderer 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();
|
||||
foreach (var id in studentIds)
|
||||
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
|
||||
// gespeicherte Stunden sinnvoll, eine gerade erst angelegte, noch ungespeicherte Stunde hat
|
||||
// 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 GroupId => _groupId;
|
||||
public Lesson? EditingLesson => _editingLesson;
|
||||
@@ -1079,6 +1083,7 @@ public partial class LessonDialogViewModel : ObservableObject
|
||||
|
||||
if (!valid) return;
|
||||
|
||||
EnsureParentSaved();
|
||||
Result = _editingLesson ?? new Lesson { UnitId = _unitId, GroupId = _groupId };
|
||||
Result.UnitId = _unitId;
|
||||
Result.GroupId = _groupId;
|
||||
|
||||
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user