Compare commits
35
Commits
aa326cf8b6
...
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 |
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,8 +233,8 @@ public interface IVorgangRepository
|
||||
/// Markiert den Vorgang als gelöscht, statt ihn hart zu entfernen (gleiches Muster wie Documentation).
|
||||
void Delete(Guid id);
|
||||
}
|
||||
/// Rein lokaler "Zurückstellen"-Zeitstempel für Dashboard-Warnungen je (StudentId, WarningTag) —
|
||||
/// kein Sync, siehe DashboardWarningSnooze.
|
||||
/// "Zurückstellen"-Zeitstempel für Dashboard-Warnungen je (StudentId, WarningTag) — wird
|
||||
/// synchronisiert, siehe DashboardWarningSnooze.
|
||||
public interface IDashboardWarningSnoozeRepository
|
||||
{
|
||||
DashboardWarningSnooze? Get(Guid studentId, string warningTag);
|
||||
|
||||
@@ -1,17 +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 rein lokaler Erinnerungs-
|
||||
/// Zeitstempel je (StudentId, WarningTag), bewusst nicht über den Sync repliziert (siehe
|
||||
/// IDashboardWarningSnoozeRepository): eher ein Job-/Fetch-Zustand als echte Fallakten-Daten wie
|
||||
/// Vorgang/Documentation.
|
||||
/// 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
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
/// 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));
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,17 @@ public class Exam
|
||||
/// <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;
|
||||
}
|
||||
@@ -68,3 +79,25 @@ public class ExamResult
|
||||
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 */ }
|
||||
}
|
||||
}
|
||||
@@ -10,37 +10,88 @@ public static class ExamScoringService
|
||||
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 verknüpfter Wiederholung genau eine Note. Andere Arbeiten bleiben erhalten.</summary>
|
||||
/// <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 available = entries.ToList();
|
||||
var byId = available.ToDictionary(x => x.Exam.Id);
|
||||
var consumed = new HashSet<Guid>();
|
||||
var result = new List<string>();
|
||||
foreach (var entry in available)
|
||||
var chains = new List<List<(Exam Exam, string Grade)>>();
|
||||
var chainByRoot = new Dictionary<Guid, List<(Exam Exam, string Grade)>>();
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (!consumed.Add(entry.Exam.Id)) continue;
|
||||
if (entry.Exam.RepeatOfExamId is { } originalId && byId.TryGetValue(originalId, out var original))
|
||||
{
|
||||
consumed.Add(originalId);
|
||||
result.Add(Choose(original.Grade, entry.Grade, entry.Exam.RepeatGradeRule, system));
|
||||
}
|
||||
else if (available.FirstOrDefault(x => x.Exam.RepeatOfExamId == entry.Exam.Id) is var repeat
|
||||
&& repeat.Exam is not null)
|
||||
{
|
||||
consumed.Add(repeat.Exam.Id);
|
||||
result.Add(Choose(entry.Grade, repeat.Grade, repeat.Exam.RepeatGradeRule, system));
|
||||
}
|
||||
else result.Add(entry.Grade);
|
||||
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;
|
||||
|
||||
@@ -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");
|
||||
@@ -113,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);
|
||||
|
||||
@@ -141,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.
|
||||
@@ -274,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);
|
||||
@@ -637,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",
|
||||
@@ -655,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);
|
||||
|
||||
@@ -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();
|
||||
@@ -906,7 +933,12 @@ public class DashboardWarningSnoozeRepository(LiteDbContext db) : IDashboardWarn
|
||||
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) => db.DashboardWarningSnoozes.Upsert(snooze);
|
||||
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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -84,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).
|
||||
@@ -973,7 +978,7 @@ public sealed class DashboardViewModelTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AttendanceWarnings_MitKuerzlichBearbeitetemVorgang_IstEntschaerftUndAmEndeSortiert()
|
||||
public void AttendanceWarnings_MitKuerzlichBearbeitetemVorgang_WandertInZurueckgestelltGruppe()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
@@ -992,12 +997,13 @@ public sealed class DashboardViewModelTests
|
||||
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||
vorgaenge: vorgaenge);
|
||||
|
||||
var items = Items(vm, AttentionKind.Attendance).ToList();
|
||||
Assert.Equal(2, items.Count);
|
||||
Assert.False(items[0].IsDefused);
|
||||
Assert.Equal(active.FullName, items[0].Title);
|
||||
Assert.True(items[1].IsDefused);
|
||||
Assert.Equal(handled.FullName, items[1].Title);
|
||||
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]
|
||||
@@ -1040,9 +1046,63 @@ public sealed class DashboardViewModelTests
|
||||
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
|
||||
warningSnoozes: snoozes);
|
||||
|
||||
var byName = Items(vm, AttentionKind.Attendance).ToDictionary(i => i.Title);
|
||||
Assert.True(byName[handled.FullName].IsDefused);
|
||||
Assert.False(byName[active.FullName].IsDefused);
|
||||
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]
|
||||
@@ -1078,7 +1138,9 @@ public sealed class DashboardViewModelTests
|
||||
Assert.Equal(student.Id, saved.StudentId);
|
||||
Assert.Equal("Absentismus", saved.WarningTag);
|
||||
Assert.Equal(today.AddDays(14), saved.SnoozedUntil);
|
||||
Assert.True(Assert.Single(Items(vm, AttentionKind.Attendance)).IsDefused);
|
||||
Assert.Empty(Items(vm, AttentionKind.Attendance));
|
||||
Assert.True(Assert.Single(DeferredItems(vm)).IsDefused);
|
||||
Assert.Equal(0, vm.AttentionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -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); }
|
||||
}
|
||||
@@ -84,4 +84,81 @@ public sealed class ExamDialogViewModelTests
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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,9 +344,9 @@ 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; }
|
||||
@@ -347,7 +371,12 @@ public class FakeDashboardWarningSnoozeRepository : IDashboardWarningSnoozeRepos
|
||||
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) { _all.RemoveAll(s => s.Id == snooze.Id); _all.Add(snooze); }
|
||||
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
|
||||
@@ -652,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(),
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -11,6 +11,46 @@ namespace LehrerApp.Desktop.Tests;
|
||||
/// 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(),
|
||||
|
||||
@@ -136,6 +136,38 @@ public sealed class StudentWarningEvidenceTests
|
||||
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()
|
||||
{
|
||||
@@ -147,7 +179,7 @@ public sealed class StudentWarningEvidenceTests
|
||||
var vm = new StudentVorgaengeViewModel(vorgaenge, documentation, new FakeStudents([_student]), BuildService());
|
||||
vm.Load(_student.Id);
|
||||
var wasDraft = false;
|
||||
vm.OnEditDocumentation = (_, editing) =>
|
||||
vm.OnEditDocumentation = (_, _, editing) =>
|
||||
{
|
||||
wasDraft = vm.IsNewDocumentationDraft(editing!);
|
||||
return Task.FromResult(editing);
|
||||
|
||||
@@ -67,4 +67,94 @@ public sealed class TeachingModeOutstandingHomeworkViewModelTests
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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"),
|
||||
|
||||
@@ -83,10 +83,12 @@ public sealed class VorgangBausteineTests
|
||||
|
||||
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("8 Fehlstunden an 2 Tagen", facts.AbsenceShort);
|
||||
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);
|
||||
@@ -98,6 +100,23 @@ public sealed class VorgangBausteineTests
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -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") };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,6 +165,7 @@ 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>();
|
||||
@@ -207,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) ──────
|
||||
@@ -233,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>();
|
||||
|
||||
@@ -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;
|
||||
|
||||
public async Task<AiAccountBalance> GetAccountBalanceAsync(string token)
|
||||
{
|
||||
using var resp = await GetAccountResponseAsync("status.php", token);
|
||||
try
|
||||
{
|
||||
return await resp.Content.ReadFromJsonAsync<AiAccountBalance>(JsonOptions)
|
||||
?? throw new AiBackendException("Das Guthaben des KI-Dienstes konnte nicht verarbeitet werden.");
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
throw new AiBackendException("Das Guthaben des KI-Dienstes konnte nicht verarbeitet werden.");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<AiUsageReport> GetUsageAsync(string token)
|
||||
{
|
||||
using var resp = await GetAccountResponseAsync("api/v1/usage.php?days=28", token);
|
||||
return AiUsageReport.Parse(await resp.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> GetAccountResponseAsync(string path, string token)
|
||||
{
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, path);
|
||||
req.Headers.Authorization = new("Bearer", token);
|
||||
HttpResponseMessage resp;
|
||||
try { resp = await http.SendAsync(req); }
|
||||
catch (HttpRequestException)
|
||||
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException)
|
||||
{
|
||||
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte Internetverbindung prüfen.");
|
||||
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte später erneut versuchen.");
|
||||
}
|
||||
|
||||
if (resp.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.");
|
||||
|
||||
var result = await resp.Content.ReadFromJsonAsync<BalanceResult>(JsonOptions);
|
||||
return result?.BalanceUsd ?? 0m;
|
||||
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;
|
||||
}
|
||||
@@ -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,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,4 +1,5 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace LehrerApp.Desktop.ViewModels;
|
||||
@@ -53,7 +54,8 @@ public sealed class AttentionItem
|
||||
/// 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
|
||||
/// nur die Optik (grau statt rot) und die Sortierung (ans Ende der Gruppe); der Schwellenwert-
|
||||
/// 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; }
|
||||
@@ -109,13 +111,34 @@ public sealed class AttentionItem
|
||||
/// <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
|
||||
|
||||
@@ -22,7 +22,10 @@ public sealed record ClassTeacherStudentFacts(StudentOption Student, string Natu
|
||||
|
||||
public int AbsentPeriods => AbsenceDays.Sum(d => d.TotalAbsentPeriods);
|
||||
public int FullDays => AbsenceDays.Count(d => d.CountsAsFullDay);
|
||||
public int UnexcusedDays => AbsenceDays.Count(d => d.IsUnexcused);
|
||||
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();
|
||||
@@ -30,15 +33,17 @@ public sealed record ClassTeacherStudentFacts(StudentOption Student, string Natu
|
||||
private string Stand => $"WebUntis-Stand {AsOf:dd.MM.yyyy}";
|
||||
|
||||
public string AbsenceShort =>
|
||||
$"{AbsentPeriods} Fehlstunde{(AbsentPeriods == 1 ? "" : "n")} an {AbsenceDays.Count} Tag{(AbsenceDays.Count == 1 ? "" : "en")} " +
|
||||
$"im Schuljahr {SchoolYear} (davon {UnexcusedDays} Tag{(UnexcusedDays == 1 ? "" : "e")} unentschuldigt, " +
|
||||
$"{FullDays} ganze Fehltag{(FullDays == 1 ? "" : "e")})";
|
||||
$"{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("Fehltage", AbsenceDays.Select(d =>
|
||||
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 =>
|
||||
@@ -50,6 +55,12 @@ public sealed record ClassTeacherStudentFacts(StudentOption Student, string Natu
|
||||
$"{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}:");
|
||||
|
||||
@@ -42,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)
|
||||
@@ -110,9 +111,9 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
||||
|
||||
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));
|
||||
|
||||
@@ -125,6 +126,25 @@ 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
|
||||
@@ -188,7 +208,7 @@ public partial class ClassTeacherCasesViewModel : ObservableObject
|
||||
|
||||
_documentationDraftId = draft.Id;
|
||||
Documentation? result;
|
||||
try { result = await OnEditDocumentation(option.Id, [option], draft); }
|
||||
try { result = await OnEditDocumentation(option.Id, [option], VorgangStudentOptions(item.Model), draft); }
|
||||
finally { _documentationDraftId = null; }
|
||||
if (result is null) return;
|
||||
_documentation.Save(result);
|
||||
@@ -242,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);
|
||||
@@ -259,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)));
|
||||
|
||||
@@ -90,6 +90,9 @@ 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;
|
||||
|
||||
@@ -66,8 +66,8 @@ public partial class DashboardViewModel : ObservableObject
|
||||
/// (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, ans Ende der Gruppe
|
||||
/// einsortiert) statt weiter rot hervorgehoben — aber nur befristet: bessert sich die zugrunde
|
||||
/// 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
|
||||
@@ -194,9 +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
|
||||
/// 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
|
||||
+ _missingHomeworkItems.Count + _latenessItems.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";
|
||||
@@ -350,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.
|
||||
@@ -427,8 +436,8 @@ public partial class DashboardViewModel : ObservableObject
|
||||
|
||||
// ── Entschärfen (Nutzer-Feedback) ─────────────────────────────────────────
|
||||
//
|
||||
// Eine der drei klassenübergreifenden Warnungen gilt als "entschärft" (grau, ans Ende ihrer
|
||||
// Gruppe sortiert), solange entweder ein offener Vorgang mit passendem Tag kürzlich bearbeitet
|
||||
// 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
|
||||
@@ -451,15 +460,24 @@ public partial class DashboardViewModel : ObservableObject
|
||||
return set;
|
||||
}
|
||||
|
||||
private HashSet<(Guid StudentId, string Tag)> BuildActiveSnoozeSet(DateOnly today) =>
|
||||
// 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)
|
||||
.Select(s => (s.StudentId, s.WarningTag.ToLowerInvariant())).ToHashSet();
|
||||
.GroupBy(s => (s.StudentId, s.WarningTag.ToLowerInvariant()))
|
||||
.ToDictionary(g => g.Key, g => g.Max(s => s.SnoozedUntil));
|
||||
|
||||
private static bool IsDefused(Guid studentId, string tag,
|
||||
HashSet<(Guid StudentId, string Tag)> recentVorgaenge, HashSet<(Guid StudentId, string Tag)> activeSnoozes)
|
||||
/// 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());
|
||||
return recentVorgaenge.Contains(key) || activeSnoozes.Contains(key);
|
||||
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
|
||||
@@ -514,15 +532,15 @@ public partial class DashboardViewModel : ObservableObject
|
||||
items.Add(new AttendanceWarningItem(student.Id, student.FullName, balance.AbsenceRatePercent));
|
||||
}
|
||||
var ordered = items
|
||||
.Select(i => (Item: i, Defused: IsDefused(i.StudentId, AbsentismusTag, recentVorgaenge, activeSnoozes)))
|
||||
.OrderBy(x => x.Defused).ThenByDescending(x => x.Item.AbsenceRatePercent);
|
||||
.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, bool isDefused) => new(
|
||||
private AttentionItem ToAttentionItem(AttendanceWarningItem w, string? defusedReason) => new(
|
||||
AttentionKind.Attendance, w.StudentName, trailingText: $"{w.AbsenceRatePercent:0.#} %",
|
||||
isWarningTrailing: true, isDefused: isDefused,
|
||||
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)));
|
||||
@@ -549,15 +567,15 @@ public partial class DashboardViewModel : ObservableObject
|
||||
items.Add(new MissingHomeworkWarningItem(student.Id, student.FullName, count));
|
||||
}
|
||||
var ordered = items
|
||||
.Select(i => (Item: i, Defused: IsDefused(i.StudentId, HausaufgabenTag, recentVorgaenge, activeSnoozes)))
|
||||
.OrderBy(x => x.Defused).ThenByDescending(x => x.Item.MissingCount);
|
||||
.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, bool isDefused) => new(
|
||||
private AttentionItem ToAttentionItem(MissingHomeworkWarningItem w, string? defusedReason) => new(
|
||||
AttentionKind.MissingHomework, w.StudentName, trailingText: $"{w.MissingCount} offen",
|
||||
isWarningTrailing: true, isDefused: isDefused,
|
||||
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)));
|
||||
@@ -588,15 +606,15 @@ public partial class DashboardViewModel : ObservableObject
|
||||
items.Add(new LatenessWarningItem(student.Id, student.FullName, count));
|
||||
}
|
||||
var ordered = items
|
||||
.Select(i => (Item: i, Defused: IsDefused(i.StudentId, VerspaetungenTag, recentVorgaenge, activeSnoozes)))
|
||||
.OrderBy(x => x.Defused).ThenByDescending(x => x.Item.LateCount);
|
||||
.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, bool isDefused) => new(
|
||||
private AttentionItem ToAttentionItem(LatenessWarningItem w, string? defusedReason) => new(
|
||||
AttentionKind.Lateness, w.StudentName, trailingText: $"{w.LateCount}× verspätet",
|
||||
isWarningTrailing: true, isDefused: isDefused,
|
||||
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)));
|
||||
@@ -958,15 +976,27 @@ public partial class DashboardViewModel : ObservableObject
|
||||
};
|
||||
|
||||
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),
|
||||
|
||||
@@ -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}";
|
||||
}
|
||||
@@ -42,6 +42,9 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
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,
|
||||
@@ -66,15 +69,17 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
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).FirstOrDefault(e => e.RepeatOfExamId == _exam.Id);
|
||||
: _exams.GetByGroup(_exam.GroupId).Where(e => e.RepeatOfExamId == _exam.Id)
|
||||
.OrderBy(e => e.Date).FirstOrDefault();
|
||||
if (repeat is null) return;
|
||||
var rule = repeat.RepeatGradeRule switch
|
||||
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} · Wiederholung: {repeat.Title} · {rule}";
|
||||
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)
|
||||
@@ -96,6 +101,7 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
}
|
||||
OnPropertyChanged(nameof(HasRepeatComparison));
|
||||
OnPropertyChanged(nameof(RepeatComparisonTitle));
|
||||
OnPropertyChanged(nameof(FollowUpLabel));
|
||||
}
|
||||
|
||||
private void LoadResults()
|
||||
@@ -226,6 +232,7 @@ 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];
|
||||
@@ -234,9 +241,8 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
var avgPercent = task.MaxPoints <= 0 || achieved.Count == 0
|
||||
? 0
|
||||
: achieved.Average() / task.MaxPoints * 100.0;
|
||||
var suffix = (task.Variant is null ? "" : $" ({task.Variant})")
|
||||
+ (task.IsBonus ? " · Bonus" : "");
|
||||
TaskAnalysis.Add(new TaskAnalysisItem(task.Nr, (task.Title ?? "") + suffix, avgPercent));
|
||||
var suffix = task.Variant is null ? "" : $" ({task.Variant})";
|
||||
TaskAnalysis.Add(new TaskAnalysisItem(labels[i] + suffix, avgPercent));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,7 +277,7 @@ public partial class ExamEvaluationDialogViewModel : ObservableObject
|
||||
if (HasRepeatComparison)
|
||||
{
|
||||
csv.AddBlankRow().AddRow("Vergleich", RepeatComparisonTitle)
|
||||
.AddRow("Schüler", "Erste Arbeit", "Wiederholung", "Zählt");
|
||||
.AddRow("Schüler", "Erste Arbeit", FollowUpLabel, "Zählt");
|
||||
foreach (var item in RepeatComparison)
|
||||
csv.AddRow(item.StudentName, item.OriginalGrade, item.RepeatGrade, item.EffectiveGrade);
|
||||
}
|
||||
@@ -316,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,11 +10,16 @@ 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 ExamGradingSettingsService? _settings;
|
||||
|
||||
public string ExamTitle => _exam.Title;
|
||||
public string ExamDateLabel => _exam.Date.ToString("dd.MM.yyyy");
|
||||
@@ -22,36 +27,109 @@ public partial class ExamGradingDialogViewModel : ObservableObject
|
||||
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();
|
||||
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);
|
||||
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
|
||||
@@ -92,6 +170,12 @@ public partial class ExamResultRow : ObservableObject
|
||||
|
||||
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)
|
||||
{
|
||||
@@ -134,7 +218,7 @@ public partial class ExamResultRow : ObservableObject
|
||||
{
|
||||
TotalPoints = Cells.Sum(c => c.IsApplicable && !c.IsInvalid ? (c.Value ?? 0) : 0);
|
||||
OnPropertyChanged(nameof(TotalPointsDisplay));
|
||||
GradeDisplay = Absent ? "abwesend" : _grading.CalculateGrade(TotalPoints,
|
||||
GradeDisplay = Absent ? "abwesend" : !HasPoints ? "" : _grading.CalculateGrade(TotalPoints,
|
||||
ExamScoringService.Maximum(_tasks, Variant), _gradingKey);
|
||||
}
|
||||
|
||||
@@ -143,9 +227,9 @@ 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(),
|
||||
@@ -172,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);
|
||||
@@ -46,11 +46,35 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
[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;
|
||||
@@ -63,7 +87,7 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
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).
|
||||
@@ -87,9 +111,10 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
_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)
|
||||
.Where(e => !groupExams.Any(r => r.RepeatOfExamId == e.Id && r.Id != editingExam?.Id))
|
||||
.OrderByDescending(e => e.Date))
|
||||
AvailableOriginalExams.Add(exam);
|
||||
|
||||
@@ -113,9 +138,13 @@ 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",
|
||||
@@ -139,13 +168,42 @@ 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) => OnPropertyChanged(nameof(HasSelectedOriginalExam));
|
||||
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;
|
||||
|
||||
@@ -156,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;
|
||||
@@ -229,10 +288,13 @@ 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()
|
||||
{
|
||||
RenumberTasks();
|
||||
TotalPoints = Tasks.Where(t => !t.IsBonus && t.VariantName != "B").Sum(t => t.MaxPoints);
|
||||
OnPropertyChanged(nameof(TotalPointsWarning));
|
||||
OnPropertyChanged(nameof(TotalPointsDisplay));
|
||||
@@ -349,10 +411,25 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
var gradingKey = BuildGradingKeyEntries();
|
||||
var gradingKeyError = _grading.ValidateGradingKey(gradingKey);
|
||||
if (gradingKeyError is not null) { GradingKeyValidation = gradingKeyError; valid = false; }
|
||||
if (SelectedOriginalExam is not null && SelectedOriginalExam.Date >= date)
|
||||
// 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 == "")
|
||||
{
|
||||
RepeatError = "Die erste Arbeit muss vor der Wiederholung liegen.";
|
||||
valid = false;
|
||||
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))
|
||||
@@ -373,6 +450,9 @@ public partial class ExamDialogViewModel : ObservableObject
|
||||
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,
|
||||
@@ -422,6 +502,8 @@ 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;
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
@@ -192,8 +214,8 @@ public partial class GradeOverviewTabViewModel : ObservableObject
|
||||
cells.Add(display);
|
||||
if (result.Grade is not null) examEntries.Add((exam, result.Grade));
|
||||
}
|
||||
numeric.AddRange(ExamScoringService.EffectiveGrades(examEntries, _gradingSystem)
|
||||
.Select(grade => (Grade: grade, Weight: 1.0)));
|
||||
var (writtenGrades, testGrades) = ExamScoringService.EffectiveGradesByKind(examEntries, _gradingSystem);
|
||||
numeric.AddRange(writtenGrades.Concat(testGrades).Select(grade => (Grade: grade, Weight: 1.0)));
|
||||
|
||||
foreach (var key in gradeColumnKeys)
|
||||
{
|
||||
@@ -207,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);
|
||||
|
||||
@@ -236,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)
|
||||
|
||||
@@ -213,7 +213,7 @@ public partial class GroupOverviewViewModel : ObservableObject
|
||||
.Select(r => (r.StudentId, Exam: e, Grade: r.Grade!)))
|
||||
.GroupBy(x => x.StudentId)
|
||||
.SelectMany(g => ExamScoringService.EffectiveGrades(
|
||||
g.Select(x => (x.Exam, x.Grade)), system))
|
||||
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);
|
||||
}
|
||||
@@ -296,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()
|
||||
{
|
||||
@@ -485,6 +509,8 @@ public partial class GroupDetailViewModel : ObservableObject
|
||||
EditExamCommand.NotifyCanExecuteChanged();
|
||||
GradeExamCommand.NotifyCanExecuteChanged();
|
||||
EvaluateExamCommand.NotifyCanExecuteChanged();
|
||||
RevealExamCommand.NotifyCanExecuteChanged();
|
||||
ExamCoverSheetsCommand.NotifyCanExecuteChanged();
|
||||
DuplicateExamCommand.NotifyCanExecuteChanged();
|
||||
DeleteExamCommand.NotifyCanExecuteChanged();
|
||||
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
|
||||
@@ -514,6 +540,8 @@ public partial class GroupDetailViewModel : ObservableObject
|
||||
EditExamCommand.NotifyCanExecuteChanged();
|
||||
GradeExamCommand.NotifyCanExecuteChanged();
|
||||
EvaluateExamCommand.NotifyCanExecuteChanged();
|
||||
RevealExamCommand.NotifyCanExecuteChanged();
|
||||
ExamCoverSheetsCommand.NotifyCanExecuteChanged();
|
||||
DuplicateExamCommand.NotifyCanExecuteChanged();
|
||||
DeleteExamCommand.NotifyCanExecuteChanged();
|
||||
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
|
||||
@@ -563,6 +591,7 @@ public partial class StudentSummary : ObservableObject
|
||||
public string AvatarTooltip { get; }
|
||||
|
||||
[ObservableProperty] private Niveau? _niveau;
|
||||
[ObservableProperty] private bool _isSupportStudent;
|
||||
|
||||
public string NiveauName
|
||||
{
|
||||
@@ -588,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));
|
||||
@@ -630,8 +662,16 @@ public class ExamSummary
|
||||
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";
|
||||
TypeLabel = e.RepeatOfExamId is not null ? (e.Tasks.Any(t => t.Variant is not null) ? "Wdh. · A/B" : "Wiederholung")
|
||||
: e.Tasks.Any(t => t.Variant is not null) ? "A/B" : "Klausur";
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||
|
||||
public enum StudentDrawMode { FullRound, Intelligent }
|
||||
|
||||
public sealed record StudentDrawGroup(Guid Id, string Name);
|
||||
|
||||
/// <summary>
|
||||
/// Steuert das eigenstaendige Ziehfenster. Die Ziehhistorie ist bewusst nur fuer die Laufzeit
|
||||
/// des Fensters gueltig; es entstehen dadurch keine zusaetzlichen personenbezogenen Datensaetze.
|
||||
/// </summary>
|
||||
public partial class RandomStudentPickerViewModel : ObservableObject
|
||||
{
|
||||
public const string FullRoundLabel = "Alle einmal, dann neu";
|
||||
public const string IntelligentLabel = "Intelligent ausgleichen";
|
||||
|
||||
private readonly IStudentRepository _students;
|
||||
private readonly IGroupMembershipRepository _memberships;
|
||||
private readonly IParticipationSessionRepository _sessions;
|
||||
private readonly IParticipationRepository _participation;
|
||||
private readonly Random _random;
|
||||
private readonly List<Student> _candidates = [];
|
||||
private readonly List<Guid> _roundBag = [];
|
||||
private readonly Dictionary<Guid, int> _drawCounts = [];
|
||||
private readonly Dictionary<Guid, ParticipationSignal> _signals = [];
|
||||
private Guid? _lastStudentId;
|
||||
|
||||
[ObservableProperty] private StudentDrawGroup? _selectedGroup;
|
||||
[ObservableProperty] private string _selectionModeName = FullRoundLabel;
|
||||
[ObservableProperty] private bool _considerParticipation = true;
|
||||
[ObservableProperty] private string _selectedStudentName = "Bereit?";
|
||||
[ObservableProperty] private string _statusText = "Wähle in den Optionen eine Lerngruppe.";
|
||||
[ObservableProperty] private bool _hasDrawnStudent;
|
||||
|
||||
public ObservableCollection<StudentDrawGroup> Groups { get; } = [];
|
||||
public string[] SelectionModeOptions { get; } = [FullRoundLabel, IntelligentLabel];
|
||||
public bool IsIntelligent => SelectionModeName == IntelligentLabel;
|
||||
public bool CanDraw => SelectedGroup is not null && _candidates.Count > 0;
|
||||
|
||||
public RandomStudentPickerViewModel(
|
||||
IStudentRepository students,
|
||||
IGroupRepository groups,
|
||||
IGroupMembershipRepository memberships,
|
||||
IParticipationSessionRepository sessions,
|
||||
IParticipationRepository participation,
|
||||
Guid? initialGroupId = null,
|
||||
Random? random = null)
|
||||
{
|
||||
_students = students;
|
||||
_memberships = memberships;
|
||||
_sessions = sessions;
|
||||
_participation = participation;
|
||||
_random = random ?? Random.Shared;
|
||||
|
||||
foreach (var group in groups.GetAll().OrderBy(g => g.Name, StringComparer.CurrentCultureIgnoreCase))
|
||||
Groups.Add(new StudentDrawGroup(group.Id, group.Name));
|
||||
|
||||
SelectedGroup = Groups.FirstOrDefault(g => g.Id == initialGroupId) ?? Groups.FirstOrDefault();
|
||||
}
|
||||
|
||||
partial void OnSelectedGroupChanged(StudentDrawGroup? value) => ReloadGroup();
|
||||
|
||||
partial void OnSelectionModeNameChanged(string value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsIntelligent));
|
||||
ResetDrawState();
|
||||
}
|
||||
|
||||
partial void OnConsiderParticipationChanged(bool value) => ResetDrawState();
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanDraw))]
|
||||
private void Draw()
|
||||
{
|
||||
var student = IsIntelligent ? DrawIntelligently() : DrawFromFullRound();
|
||||
_drawCounts[student.Id] = _drawCounts.GetValueOrDefault(student.Id) + 1;
|
||||
_lastStudentId = student.Id;
|
||||
SelectedStudentName = student.FullName;
|
||||
HasDrawnStudent = true;
|
||||
UpdateStatus();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void Reset() => ResetDrawState();
|
||||
|
||||
private void ReloadGroup()
|
||||
{
|
||||
_candidates.Clear();
|
||||
_signals.Clear();
|
||||
|
||||
if (SelectedGroup is not null)
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var activeIds = _memberships.GetByGroup(SelectedGroup.Id)
|
||||
.Where(m => GroupMembershipService.IsActiveOn(m, today))
|
||||
.Select(m => m.StudentId)
|
||||
.ToHashSet();
|
||||
_candidates.AddRange(_students.GetByGroup(SelectedGroup.Id)
|
||||
.Where(s => s.IsActive && activeIds.Contains(s.Id))
|
||||
.OrderBy(s => s.LastName, StringComparer.CurrentCultureIgnoreCase)
|
||||
.ThenBy(s => s.FirstName, StringComparer.CurrentCultureIgnoreCase));
|
||||
LoadParticipationSignals(SelectedGroup.Id);
|
||||
}
|
||||
|
||||
ResetDrawState();
|
||||
OnPropertyChanged(nameof(CanDraw));
|
||||
DrawCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
private void LoadParticipationSignals(Guid groupId)
|
||||
{
|
||||
var sessionIds = _sessions.GetByGroup(groupId).Select(s => s.Id).ToList();
|
||||
var entries = sessionIds.SelectMany(_participation.GetBySession).ToList();
|
||||
|
||||
foreach (var student in _candidates)
|
||||
{
|
||||
var own = entries.Where(e => e.StudentId == student.Id).ToList();
|
||||
var activity = own.Sum(e => e.RaisedHandCount + e.CalledOnCount);
|
||||
var values = own.SelectMany(e => e.Ratings).Select(r => Math.Clamp(r.Value, -2, 2)).ToList();
|
||||
_signals[student.Id] = new ParticipationSignal(
|
||||
activity,
|
||||
values.Count == 0 ? null : values.Average());
|
||||
}
|
||||
}
|
||||
|
||||
private Student DrawFromFullRound()
|
||||
{
|
||||
if (_roundBag.Count == 0)
|
||||
{
|
||||
_roundBag.AddRange(_candidates.Select(s => s.Id));
|
||||
for (var i = _roundBag.Count - 1; i > 0; i--)
|
||||
{
|
||||
var swap = _random.Next(i + 1);
|
||||
(_roundBag[i], _roundBag[swap]) = (_roundBag[swap], _roundBag[i]);
|
||||
}
|
||||
}
|
||||
|
||||
var id = _roundBag[^1];
|
||||
_roundBag.RemoveAt(_roundBag.Count - 1);
|
||||
return _candidates.Single(s => s.Id == id);
|
||||
}
|
||||
|
||||
private Student DrawIntelligently()
|
||||
{
|
||||
var maxActivity = Math.Max(1, _signals.Values.Select(s => s.Activity).DefaultIfEmpty().Max());
|
||||
var eligible = _candidates.Count > 1
|
||||
? _candidates.Where(student => student.Id != _lastStudentId)
|
||||
: _candidates;
|
||||
var weighted = eligible.Select(student =>
|
||||
{
|
||||
var weight = 1.0 / (1.0 + 1.5 * _drawCounts.GetValueOrDefault(student.Id));
|
||||
if (ConsiderParticipation && _signals.TryGetValue(student.Id, out var signal))
|
||||
{
|
||||
var activityRatio = signal.Activity / (double)maxActivity;
|
||||
weight *= 1.65 - activityRatio; // wenig Aktive werden wahrscheinlicher gezogen
|
||||
if (signal.AverageRating is { } rating)
|
||||
weight *= 1.0 - Math.Clamp(rating, -2, 2) * 0.175; // starke spaeter, schwache frueher
|
||||
}
|
||||
return (Student: student, Weight: Math.Max(0.01, weight));
|
||||
}).ToList();
|
||||
|
||||
var point = _random.NextDouble() * weighted.Sum(x => x.Weight);
|
||||
foreach (var item in weighted)
|
||||
{
|
||||
point -= item.Weight;
|
||||
if (point <= 0) return item.Student;
|
||||
}
|
||||
return weighted[^1].Student;
|
||||
}
|
||||
|
||||
private void ResetDrawState()
|
||||
{
|
||||
_roundBag.Clear();
|
||||
_drawCounts.Clear();
|
||||
_lastStudentId = null;
|
||||
HasDrawnStudent = false;
|
||||
SelectedStudentName = "Bereit?";
|
||||
UpdateStatus();
|
||||
}
|
||||
|
||||
private void UpdateStatus()
|
||||
{
|
||||
StatusText = _candidates.Count switch
|
||||
{
|
||||
0 when SelectedGroup is null => "Wähle in den Optionen eine Lerngruppe.",
|
||||
0 => "In dieser Lerngruppe sind heute keine aktiven Schüler.",
|
||||
_ when !HasDrawnStudent => $"{_candidates.Count} Schüler stehen zur Auswahl.",
|
||||
_ when !IsIntelligent && _roundBag.Count == 0 => "Alle waren dran. Der nächste Zug startet eine neue Runde.",
|
||||
_ when !IsIntelligent => $"Noch {_roundBag.Count} bis zur nächsten Runde.",
|
||||
_ => "Nächste Ziehung bereit.",
|
||||
};
|
||||
}
|
||||
|
||||
private sealed record ParticipationSignal(int Activity, double? AverageRating);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using LehrerApp.Core.Models;
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||
|
||||
/// Ein Zwischenstand-Durchgang: Stichtag und Anlass gelten für alle gewählten Schüler.
|
||||
public sealed record InterimRunOptions(DateOnly Date, string Occasion, IReadOnlyCollection<Guid> StudentIds);
|
||||
|
||||
// ── Zwischenstand-Modus des Assistenten (2.7.5) ──────────────────────────────
|
||||
//
|
||||
// Mit InterimRunOptions gestartet, geht der Assistent nur die gewählten Schüler durch und
|
||||
// notiert je Schüler eine vorläufige schriftliche, mündliche und Gesamtnote zum Stichtag —
|
||||
// als InterimGrade, ohne die Zeugnisnote (ReportGrade) anzufassen. Vorgeschlagen wird der
|
||||
// Stand aus InterimGradeCalculator, also inklusive des laufenden Mitarbeits-Abschnitts.
|
||||
public partial class ReportGradeAssistantViewModel
|
||||
{
|
||||
[ObservableProperty] private string? _interimWritten;
|
||||
[ObservableProperty] private string? _interimOral;
|
||||
[ObservableProperty] private string? _interimOverall;
|
||||
[ObservableProperty] private string? _interimNote;
|
||||
[ObservableProperty] private string _interimWrittenError = "";
|
||||
[ObservableProperty] private string _interimOralError = "";
|
||||
[ObservableProperty] private string _interimOverallError = "";
|
||||
[ObservableProperty] private bool _hasInterimEntry;
|
||||
|
||||
/// Alle bisher notierten Zwischenstände des gewählten Schülers — in beiden Modi sichtbar.
|
||||
public ObservableCollection<AssistantInterimRow> InterimEntries { get; } = [];
|
||||
public bool HasInterimEntries => InterimEntries.Count > 0;
|
||||
|
||||
public bool IsInterimMode => _interim is not null;
|
||||
public bool IsReportMode => _interim is null;
|
||||
public string WindowTitle => IsInterimMode ? "Zwischenstand" : "Zeugnisnoten-Assistent";
|
||||
public string InterimTitle => _interim is null
|
||||
? "" : $"Zwischenstand {_interim.Date:dd.MM.yyyy} · {_interim.Occasion}";
|
||||
|
||||
/// Startet aus dem Zeugnisnoten-Modus einen Zwischenstand für den gezeigten Schüler; vom
|
||||
/// Fenster gesetzt, das den Startdialog öffnen kann.
|
||||
public Func<Guid, Task>? OnStartInterim { get; set; }
|
||||
|
||||
private InterimGrade? CurrentInterim(Guid studentId) => _interim is null ? null
|
||||
: _interimGrades.GetByStudentAndGroup(studentId, _groupId)
|
||||
.FirstOrDefault(g => g.Date == _interim.Date && g.Occasion == _interim.Occasion);
|
||||
|
||||
private void RefreshInterimItem(AssistantStudentItem item)
|
||||
{
|
||||
var existing = CurrentInterim(item.StudentId);
|
||||
if (existing is not null)
|
||||
item.Update(existing.OverallValue, AssistantGradeStatus.Noted);
|
||||
else
|
||||
item.Update(_interimCalculator.Calculate(item.StudentId, _interim!.Date, RoundingRule).Result.Rounded ?? "–",
|
||||
AssistantGradeStatus.Open);
|
||||
}
|
||||
|
||||
private void ShowInterim(Guid studentId)
|
||||
{
|
||||
var interim = _interimCalculator.Calculate(studentId, _interim!.Date, RoundingRule);
|
||||
var result = interim.Result;
|
||||
|
||||
_calculatedValue = result.Rounded;
|
||||
CalculatedDisplay = result.Rounded ?? "–";
|
||||
var between = result.Value is { } value ? ReportGradeCalculator.BetweenGrades(value) : null;
|
||||
BorderlineHint = between is null ? "" : $"Liegt genau {between} — pädagogische Entscheidung.";
|
||||
CalculationDetail = result.Value is null
|
||||
? "Noch keine Leistungen bis zum Stichtag."
|
||||
: $"Stand {_interim.Date:dd.MM.yyyy} · gewichtet {Format(result.Value.Value)} vor Rundung";
|
||||
|
||||
var scheme = _calculator.Scheme;
|
||||
Tiles.Clear();
|
||||
Tiles.Add(BucketTile("Schriftlich", result.Written, scheme.ExamsPercent));
|
||||
Tiles.Add(new AssistantTile("Mitarbeit",
|
||||
result.Participation.HasValue ? Format(result.Participation.Value) : "–",
|
||||
$"{scheme.ParticipationPercent:0.#} %" +
|
||||
(interim.RunningParticipation is null ? "" : $" · laufender Abschnitt: {interim.RunningParticipation}")));
|
||||
Tiles.Add(BucketTile("Sonstige", result.Other, scheme.OtherPercent));
|
||||
|
||||
// Bereits notiert: der notierte Stand gilt. Sonst der berechnete Vorschlag zum Anpassen.
|
||||
var existing = CurrentInterim(studentId);
|
||||
HasInterimEntry = existing is not null;
|
||||
InterimWritten = existing is not null ? existing.WrittenValue : RoundOrNull(result.Written);
|
||||
InterimOral = existing is not null ? existing.OralValue : RoundOrNull(result.Participation);
|
||||
InterimOverall = existing is not null ? existing.OverallValue : result.Rounded;
|
||||
InterimNote = existing?.Note;
|
||||
}
|
||||
|
||||
private string? RoundOrNull(double? value) => value.HasValue ? _calculator.Round(value.Value, RoundingRule) : null;
|
||||
|
||||
private void LoadInterimEntries(Guid studentId)
|
||||
{
|
||||
InterimEntries.Clear();
|
||||
foreach (var entry in _interimGrades.GetByStudentAndGroup(studentId, _groupId)
|
||||
.OrderByDescending(g => g.Date).ThenByDescending(g => g.UpdatedAt))
|
||||
InterimEntries.Add(new AssistantInterimRow(entry));
|
||||
OnPropertyChanged(nameof(HasInterimEntries));
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void NoteInterim() => TryNoteInterim();
|
||||
|
||||
[RelayCommand]
|
||||
private void NoteInterimAndNext()
|
||||
{
|
||||
if (!TryNoteInterim()) return;
|
||||
if (CanGoNextStudent) NextStudent();
|
||||
}
|
||||
|
||||
private bool TryNoteInterim()
|
||||
{
|
||||
if (_interim is null || SelectedStudent is null) return false;
|
||||
ClearErrors();
|
||||
var valid = true;
|
||||
if (!IsGradeOrEmpty(InterimWritten)) { InterimWrittenError = "Keine gültige Note."; valid = false; }
|
||||
if (!IsGradeOrEmpty(InterimOral)) { InterimOralError = "Keine gültige Note."; valid = false; }
|
||||
if (NullIfEmpty(InterimOverall) is null) { InterimOverallError = "Gesamtnote erforderlich."; valid = false; }
|
||||
else if (!IsGradeOrEmpty(InterimOverall)) { InterimOverallError = "Keine gültige Note."; valid = false; }
|
||||
if (!valid) return false;
|
||||
|
||||
var studentId = SelectedStudent.StudentId;
|
||||
var entry = CurrentInterim(studentId) ?? new InterimGrade
|
||||
{
|
||||
StudentId = studentId, GroupId = _groupId, Date = _interim.Date, Occasion = _interim.Occasion,
|
||||
};
|
||||
entry.WrittenValue = NullIfEmpty(InterimWritten);
|
||||
entry.OralValue = NullIfEmpty(InterimOral);
|
||||
entry.OverallValue = NullIfEmpty(InterimOverall)!;
|
||||
entry.Note = NullIfEmpty(InterimNote);
|
||||
_interimGrades.Save(entry);
|
||||
|
||||
RefreshItem(SelectedStudent);
|
||||
ShowStudent();
|
||||
StatusMessage = "Zwischenstand notiert.";
|
||||
return true;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RemoveInterim()
|
||||
{
|
||||
if (SelectedStudent is null || CurrentInterim(SelectedStudent.StudentId) is not { } entry) return;
|
||||
_interimGrades.Delete(entry.Id);
|
||||
RefreshItem(SelectedStudent);
|
||||
ShowStudent();
|
||||
StatusMessage = "Zwischenstand entfernt.";
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task StartInterim()
|
||||
{
|
||||
if (OnStartInterim is null || SelectedStudent is null) return;
|
||||
await OnStartInterim(SelectedStudent.StudentId);
|
||||
ShowStudent();
|
||||
}
|
||||
}
|
||||
|
||||
public class AssistantInterimRow(InterimGrade entry)
|
||||
{
|
||||
public string Title { get; } = $"{entry.Date:dd.MM.yyyy} · {entry.Occasion}";
|
||||
public string OverallValue { get; } = entry.OverallValue;
|
||||
public string Detail { get; } = string.Join(" · ", new[]
|
||||
{
|
||||
entry.WrittenValue is null ? null : $"schriftlich {entry.WrittenValue}",
|
||||
entry.OralValue is null ? null : $"mündlich {entry.OralValue}",
|
||||
}.Where(part => part is not null));
|
||||
public string Note { get; } = entry.Note ?? "";
|
||||
}
|
||||
@@ -0,0 +1,692 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
|
||||
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||
|
||||
// ── Zeugnisnoten-Assistent ───────────────────────────────────────────────────
|
||||
//
|
||||
// Geht die Lerngruppe Schüler für Schüler durch und zieht alles zusammen, was für die
|
||||
// Halbjahres- bzw. Endjahresnote zählt: berechnete Note mit Teilbereichen, Mitarbeitsgraph
|
||||
// (abschnittsweise blätterbar oder als durchgehender Verlauf), Arbeiten und Einzelnoten.
|
||||
// Ergänzt den Zeugnisnoten-Dialog (2.4), ersetzt ihn nicht — beide schreiben dieselben
|
||||
// ReportGrade-Datensätze (gleiche Period-Bezeichnungen), der Dialog bleibt die schnelle Liste.
|
||||
//
|
||||
// Halbjahre sind eigenständig: Leistungen aus dem 1. Halbjahr zählen nicht in die Note des
|
||||
// 2. Halbjahrs, werden dort aber ausgegraut als Kontext gezeigt (Trends). Die Endjahresnote
|
||||
// wird aus den Halbjahresnoten verrechnet, nicht aus allen Einzelleistungen; in Klasse 10 lassen
|
||||
// sich dafür zusätzlich Projekt- und mündliche Prüfung eintragen (siehe ReportGradeCalculator).
|
||||
public partial class ReportGradeAssistantViewModel : ObservableObject
|
||||
{
|
||||
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
|
||||
|
||||
private const int ExamGradeLevel = 10;
|
||||
|
||||
private readonly IReportGradeRepository _reportGrades;
|
||||
private readonly IParticipationRepository _participation;
|
||||
private readonly AttendanceBalanceService _attendanceBalance;
|
||||
private readonly GradingService _grading;
|
||||
private readonly ParticipationTimelineBuilder _timeline;
|
||||
private readonly ReportGradeCalculator _calculator;
|
||||
private readonly InterimGradeCalculator _interimCalculator;
|
||||
private readonly IInterimGradeRepository _interimGrades;
|
||||
private readonly InterimRunOptions? _interim;
|
||||
private readonly Guid _groupId;
|
||||
private readonly int _gradeLevel;
|
||||
private readonly DateOnly _today;
|
||||
|
||||
private readonly List<Student> _allStudents;
|
||||
private readonly Dictionary<Guid, GroupMembership> _membershipsByStudent;
|
||||
private readonly List<ParticipationSection> _sections;
|
||||
|
||||
private string? _calculatedValue;
|
||||
private bool _showing;
|
||||
private List<SectionView> _sectionViews = [];
|
||||
private int _sectionIndex;
|
||||
private bool _loading;
|
||||
|
||||
public string GroupLabel { get; }
|
||||
|
||||
[ObservableProperty] private ParticipationPeriodOption _selectedPeriod;
|
||||
[ObservableProperty] private RoundingRule _roundingRule = RoundingRule.Commercial;
|
||||
[ObservableProperty] private string _schemeSummary = "";
|
||||
[ObservableProperty] private AssistantStudentItem? _selectedStudent;
|
||||
[ObservableProperty] private bool _showPreviousHalf = true;
|
||||
|
||||
// Kopf: Note des gewählten Schülers
|
||||
[ObservableProperty] private string _calculatedDisplay = "–";
|
||||
[ObservableProperty] private string _calculationDetail = "";
|
||||
[ObservableProperty] private string _borderlineHint = "";
|
||||
[ObservableProperty] private string _absenceRateDisplay = "";
|
||||
[ObservableProperty] private string _absenceRateColorHex = "#8A8A8A";
|
||||
[ObservableProperty] private string? _overrideValue;
|
||||
[ObservableProperty] private string? _overrideReason;
|
||||
[ObservableProperty] private string _overrideReasonError = "";
|
||||
[ObservableProperty] private bool _isLocked;
|
||||
[ObservableProperty] private string _statusMessage = "";
|
||||
|
||||
// Klasse 10: Prüfungsnoten, die in der Endjahresnote wie ein weiteres Halbjahr zählen
|
||||
[ObservableProperty] private string? _projectExamGrade;
|
||||
[ObservableProperty] private string? _oralExamGrade;
|
||||
[ObservableProperty] private string? _writtenExamGrade;
|
||||
[ObservableProperty] private string? _additionalOralExamGrade;
|
||||
[ObservableProperty] private string _projectExamGradeError = "";
|
||||
[ObservableProperty] private string _oralExamGradeError = "";
|
||||
[ObservableProperty] private string _writtenExamGradeError = "";
|
||||
[ObservableProperty] private string _additionalOralExamGradeError = "";
|
||||
|
||||
// Mitarbeitsgraph
|
||||
[ObservableProperty] private bool _isSectionMode = true;
|
||||
[ObservableProperty] private double _timelineZoom = 1.0;
|
||||
[ObservableProperty] private IReadOnlyList<WizardSectionGroup> _chartGroups = [];
|
||||
[ObservableProperty] private string _sectionTitle = "";
|
||||
[ObservableProperty] private string _sectionPosition = "";
|
||||
|
||||
public List<ParticipationPeriodOption> PeriodOptions { get; } =
|
||||
[
|
||||
new(ParticipationPeriod.H1, "1. Halbjahr"),
|
||||
new(ParticipationPeriod.H2, "2. Halbjahr"),
|
||||
new(ParticipationPeriod.FullYear, "Gesamtes Schuljahr"),
|
||||
];
|
||||
public string[] RoundingOptions { get; } = RoundingRuleDisplay.Options;
|
||||
|
||||
// Für die ComboBox: deutsche Anzeige statt des rohen Enum-Namens.
|
||||
public string RoundingRuleName
|
||||
{
|
||||
get => RoundingRuleDisplay.Label(RoundingRule);
|
||||
set => RoundingRule = RoundingRuleDisplay.FromLabel(value);
|
||||
}
|
||||
|
||||
public ObservableCollection<AssistantStudentItem> Students { get; } = [];
|
||||
public ObservableCollection<AssistantTile> Tiles { get; } = [];
|
||||
public ObservableCollection<AssistantWorkCard> Works { get; } = [];
|
||||
public ObservableCollection<AssistantGradeRow> ParticipationGrades { get; } = [];
|
||||
public ObservableCollection<AssistantGradeRow> OtherGrades { get; } = [];
|
||||
|
||||
public bool HasStudent => SelectedStudent is not null;
|
||||
public string StudentName => SelectedStudent?.Name ?? "";
|
||||
public string ProgressText => SelectedStudent is null
|
||||
? "" : $"{Students.IndexOf(SelectedStudent) + 1} / {Students.Count}";
|
||||
public string LockLabel => IsLocked ? "Entsperren" : "Festschreiben";
|
||||
public string FinalDisplay => !string.IsNullOrWhiteSpace(OverrideValue) ? OverrideValue!.Trim() : CalculatedDisplay;
|
||||
public bool IsContinuousMode => !IsSectionMode;
|
||||
/// Nur im 2. Halbjahr gibt es ein Vorhalbjahr, das als Kontext eingeblendet werden kann.
|
||||
public bool CanShowPreviousHalf => SelectedPeriod.Period == ParticipationPeriod.H2;
|
||||
/// Projekt- und mündliche Prüfung gibt es nur in Klasse 10 und nur für die Endjahresnote.
|
||||
public bool CanEnterExamGrades =>
|
||||
SelectedPeriod.Period == ParticipationPeriod.FullYear && _gradeLevel == ExamGradeLevel;
|
||||
public bool HasWorks => Works.Count > 0;
|
||||
public bool HasParticipationGrades => ParticipationGrades.Count > 0;
|
||||
public bool HasOtherGrades => OtherGrades.Count > 0;
|
||||
|
||||
public ReportGradeAssistantViewModel(IGradeRepository grades, IExamRepository exams,
|
||||
IExamResultRepository results, IStudentRepository students, IGroupMembershipRepository memberships,
|
||||
IGradingSchemeRepository schemes, IReportGradeRepository reportGrades,
|
||||
IParticipationSessionRepository participationSessions, IParticipationRepository participation,
|
||||
IParticipationAspectRepository aspects, IParticipationSectionRepository sections,
|
||||
IInterimGradeRepository interimGrades,
|
||||
AttendanceBalanceService attendanceBalance, GradingService grading,
|
||||
Guid groupId, GroupType groupType, GradingSystem gradingSystem, string groupLabel, string schoolYear,
|
||||
int gradeLevel, DateOnly? today = null, InterimRunOptions? interim = null)
|
||||
{
|
||||
_reportGrades = reportGrades; _participation = participation;
|
||||
_interimGrades = interimGrades; _interim = interim;
|
||||
_attendanceBalance = attendanceBalance; _grading = grading;
|
||||
_groupId = groupId; _gradeLevel = gradeLevel;
|
||||
_today = today ?? DateOnly.FromDateTime(DateTime.Today);
|
||||
GroupLabel = groupLabel;
|
||||
|
||||
_membershipsByStudent = memberships.GetByGroup(groupId).ToDictionary(m => m.StudentId);
|
||||
_allStudents = students.GetByGroup(groupId).OrderBy(s => s.LastName).ThenBy(s => s.FirstName).ToList();
|
||||
_sections = sections.GetByGroup(groupId).OrderBy(s => s.StartDate).ToList();
|
||||
_timeline = new ParticipationTimelineBuilder(participationSessions, participation, aspects, exams, results,
|
||||
grades, _membershipsByStudent, grading, groupId, gradingSystem);
|
||||
_calculator = new ReportGradeCalculator(grades, exams, results, schemes, reportGrades,
|
||||
_membershipsByStudent, grading, groupId, groupType, gradingSystem, schoolYear);
|
||||
|
||||
_interimCalculator = new InterimGradeCalculator(_calculator, _timeline, _sections);
|
||||
|
||||
// Vorbelegung: das Halbjahr, in dem wir uns gerade befinden — bzw. das des Stichtags.
|
||||
var half = _interimCalculator.HalfOf(_interim?.Date ?? _today);
|
||||
_selectedPeriod = PeriodOptions.First(p => p.Period == half);
|
||||
Reload();
|
||||
}
|
||||
|
||||
partial void OnSelectedPeriodChanged(ParticipationPeriodOption value)
|
||||
{
|
||||
OnPropertyChanged(nameof(CanShowPreviousHalf));
|
||||
OnPropertyChanged(nameof(CanEnterExamGrades));
|
||||
Reload();
|
||||
}
|
||||
|
||||
partial void OnRoundingRuleChanged(RoundingRule value) => Reload();
|
||||
partial void OnShowPreviousHalfChanged(bool value) => ShowStudent();
|
||||
|
||||
partial void OnSelectedStudentChanged(AssistantStudentItem? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(HasStudent));
|
||||
OnPropertyChanged(nameof(StudentName));
|
||||
OnPropertyChanged(nameof(ProgressText));
|
||||
PreviousStudentCommand.NotifyCanExecuteChanged();
|
||||
NextStudentCommand.NotifyCanExecuteChanged();
|
||||
if (!_loading) ShowStudent();
|
||||
}
|
||||
|
||||
partial void OnIsSectionModeChanged(bool value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsContinuousMode));
|
||||
ApplyChartMode();
|
||||
}
|
||||
|
||||
partial void OnIsLockedChanged(bool value) => OnPropertyChanged(nameof(LockLabel));
|
||||
partial void OnOverrideValueChanged(string? value) => OnPropertyChanged(nameof(FinalDisplay));
|
||||
partial void OnCalculatedDisplayChanged(string value) => OnPropertyChanged(nameof(FinalDisplay));
|
||||
|
||||
// Eine eingetippte Prüfungsnote wirkt sofort auf die angezeigte Berechnung, gespeichert wird
|
||||
// sie erst mit der Zeugnisnote.
|
||||
partial void OnProjectExamGradeChanged(string? value) { if (!_showing) ShowCalculation(); }
|
||||
partial void OnOralExamGradeChanged(string? value) { if (!_showing) ShowCalculation(); }
|
||||
partial void OnWrittenExamGradeChanged(string? value) { if (!_showing) ShowCalculation(); }
|
||||
partial void OnAdditionalOralExamGradeChanged(string? value) { if (!_showing) ShowCalculation(); }
|
||||
|
||||
private void ClearErrors()
|
||||
{
|
||||
OverrideReasonError = ""; ProjectExamGradeError = ""; OralExamGradeError = "";
|
||||
WrittenExamGradeError = ""; AdditionalOralExamGradeError = "";
|
||||
InterimWrittenError = ""; InterimOralError = ""; InterimOverallError = "";
|
||||
}
|
||||
|
||||
// ── Laden ────────────────────────────────────────────────────────────────
|
||||
|
||||
private void Reload()
|
||||
{
|
||||
_calculator.Reload();
|
||||
SchemeSummary = _calculator.SchemeSummary;
|
||||
|
||||
var (from, to) = _calculator.Range(SelectedPeriod.Period);
|
||||
var previousId = SelectedStudent?.StudentId;
|
||||
|
||||
_loading = true;
|
||||
Students.Clear();
|
||||
foreach (var student in _allStudents)
|
||||
{
|
||||
if (_interim is not null && !_interim.StudentIds.Contains(student.Id)) continue;
|
||||
if (_membershipsByStudent.TryGetValue(student.Id, out var membership)
|
||||
&& !GroupMembershipService.Overlaps(membership, from, to)) continue;
|
||||
var item = new AssistantStudentItem(student.Id, student.FullName);
|
||||
RefreshItem(item);
|
||||
Students.Add(item);
|
||||
}
|
||||
SelectedStudent = Students.FirstOrDefault(s => s.StudentId == previousId) ?? Students.FirstOrDefault();
|
||||
_loading = false;
|
||||
|
||||
OnPropertyChanged(nameof(ProgressText));
|
||||
PreviousStudentCommand.NotifyCanExecuteChanged();
|
||||
NextStudentCommand.NotifyCanExecuteChanged();
|
||||
ShowStudent();
|
||||
}
|
||||
|
||||
private void RefreshItem(AssistantStudentItem item)
|
||||
{
|
||||
if (_interim is not null) { RefreshInterimItem(item); return; }
|
||||
var record = _reportGrades.GetByStudentGroupPeriod(item.StudentId, _groupId, SelectedPeriod.Label);
|
||||
var calculated = record is { IsLocked: true }
|
||||
? NullIfEmpty(record.CalculatedValue)
|
||||
: _calculator.Calculate(item.StudentId, SelectedPeriod.Period, RoundingRule).Rounded;
|
||||
item.Update(NullIfEmpty(record?.OverrideValue) ?? calculated ?? "–", record switch
|
||||
{
|
||||
null => AssistantGradeStatus.Open,
|
||||
{ IsLocked: true } => AssistantGradeStatus.Locked,
|
||||
_ => AssistantGradeStatus.Saved,
|
||||
});
|
||||
}
|
||||
|
||||
// ── Berechnung ───────────────────────────────────────────────────────────
|
||||
|
||||
// ── Anzeige des gewählten Schülers ───────────────────────────────────────
|
||||
|
||||
private void ShowStudent()
|
||||
{
|
||||
StatusMessage = "";
|
||||
ClearErrors();
|
||||
Works.Clear(); ParticipationGrades.Clear(); OtherGrades.Clear();
|
||||
|
||||
if (SelectedStudent is null)
|
||||
{
|
||||
_calculatedValue = null;
|
||||
Tiles.Clear();
|
||||
CalculatedDisplay = "–"; CalculationDetail = ""; BorderlineHint = ""; AbsenceRateDisplay = "";
|
||||
OverrideValue = null; OverrideReason = null; IsLocked = false;
|
||||
InterimEntries.Clear();
|
||||
OnPropertyChanged(nameof(HasInterimEntries));
|
||||
_sectionViews = [];
|
||||
ApplyChartMode();
|
||||
NotifyLists();
|
||||
return;
|
||||
}
|
||||
|
||||
var studentId = SelectedStudent.StudentId;
|
||||
var (from, to) = _calculator.Range(SelectedPeriod.Period);
|
||||
// Zwischenstand: alles nach dem Stichtag bleibt außen vor, auch in der Anzeige.
|
||||
if (_interim is not null && _interim.Date < to) to = _interim.Date;
|
||||
_membershipsByStudent.TryGetValue(studentId, out var membership);
|
||||
|
||||
var record = _interim is null
|
||||
? _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, SelectedPeriod.Label) : null;
|
||||
_showing = true;
|
||||
IsLocked = record is { IsLocked: true };
|
||||
OverrideValue = record?.OverrideValue;
|
||||
OverrideReason = record?.OverrideReason;
|
||||
ProjectExamGrade = CanEnterExamGrades ? record?.ProjectExamGrade : null;
|
||||
OralExamGrade = CanEnterExamGrades ? record?.OralExamGrade : null;
|
||||
WrittenExamGrade = CanEnterExamGrades ? record?.WrittenExamGrade : null;
|
||||
AdditionalOralExamGrade = CanEnterExamGrades ? record?.AdditionalOralExamGrade : null;
|
||||
_showing = false;
|
||||
|
||||
if (_interim is not null) ShowInterim(studentId); else ShowCalculation();
|
||||
LoadInterimEntries(studentId);
|
||||
ShowAbsenceRate(studentId, from, to);
|
||||
|
||||
// Im 2. Halbjahr auf Wunsch das Vorhalbjahr als Kontext mitzeigen — ohne Einfluss auf die Note.
|
||||
var displayFrom = CanShowPreviousHalf && ShowPreviousHalf
|
||||
? _calculator.Range(ParticipationPeriod.FullYear).From : from;
|
||||
BuildWorks(studentId, membership, displayFrom, from, to);
|
||||
BuildGradeRows(studentId, membership, displayFrom, from, to);
|
||||
BuildSections(studentId, displayFrom, to);
|
||||
NotifyLists();
|
||||
}
|
||||
|
||||
/// Berechnete Note und Teilnoten-Kacheln des gewählten Schülers.
|
||||
private void ShowCalculation()
|
||||
{
|
||||
if (SelectedStudent is null) return;
|
||||
var studentId = SelectedStudent.StudentId;
|
||||
var period = SelectedPeriod.Period;
|
||||
// In Klasse 10 gelten die gerade eingetragenen Prüfungsnoten, sonst die gespeicherten.
|
||||
YearExamGrades? typed = CanEnterExamGrades
|
||||
? new YearExamGrades(ProjectExamGrade, OralExamGrade, WrittenExamGrade, AdditionalOralExamGrade)
|
||||
: null;
|
||||
var result = _calculator.Calculate(studentId, period, RoundingRule, typed);
|
||||
|
||||
// Festgeschrieben heißt: der gespeicherte Stand gilt, es wird nicht neu berechnet.
|
||||
_calculatedValue = IsLocked
|
||||
? NullIfEmpty(_reportGrades.GetByStudentGroupPeriod(studentId, _groupId, SelectedPeriod.Label)?.CalculatedValue)
|
||||
: result.Rounded;
|
||||
CalculatedDisplay = _calculatedValue ?? "–";
|
||||
// Genau auf der Grenze entscheidet die gewählte Rundung nur formal — der Hinweis macht
|
||||
// sichtbar, dass hier die Lehrkraft entscheiden sollte.
|
||||
var between = !IsLocked && result.Value is { } value ? ReportGradeCalculator.BetweenGrades(value) : null;
|
||||
BorderlineHint = between is null ? "" : $"Liegt genau {between} — pädagogische Entscheidung.";
|
||||
|
||||
Tiles.Clear();
|
||||
if (period == ParticipationPeriod.FullYear)
|
||||
{
|
||||
var parts = _calculator.YearParts(studentId, RoundingRule, typed);
|
||||
foreach (var part in parts)
|
||||
Tiles.Add(new AssistantTile(part.Label, part.Final ?? "–", part.Hint));
|
||||
CalculationDetail = result.Value is null
|
||||
? "Noch keine Halbjahresnote vorhanden."
|
||||
: $"aus {parts.Count(p => p.Final is not null)} Teilnoten {Format(result.Value.Value)} vor Rundung";
|
||||
}
|
||||
else
|
||||
{
|
||||
var scheme = _calculator.Scheme;
|
||||
Tiles.Add(BucketTile("Schriftlich", result.Written, scheme.ExamsPercent));
|
||||
Tiles.Add(BucketTile("Mitarbeit", result.Participation, scheme.ParticipationPercent));
|
||||
Tiles.Add(BucketTile("Sonstige", result.Other, scheme.OtherPercent));
|
||||
CalculationDetail = result.Value is null
|
||||
? "Noch keine Leistungen im gewählten Zeitraum."
|
||||
: $"gewichtet {Format(result.Value.Value)} vor Rundung";
|
||||
}
|
||||
}
|
||||
|
||||
private void NotifyLists()
|
||||
{
|
||||
OnPropertyChanged(nameof(HasWorks));
|
||||
OnPropertyChanged(nameof(HasParticipationGrades));
|
||||
OnPropertyChanged(nameof(HasOtherGrades));
|
||||
}
|
||||
|
||||
private static AssistantTile BucketTile(string label, double? average, double percent) =>
|
||||
new(label, average.HasValue ? Format(average.Value) : "–", $"{percent:0.#} %");
|
||||
|
||||
private void ShowAbsenceRate(Guid studentId, DateOnly from, DateOnly to)
|
||||
{
|
||||
// Wie im Zeugnisnoten-Dialog (2.4.5): nur Sitzungen dieser Gruppe im gewählten Zeitraum.
|
||||
var attendance = _timeline.Sessions
|
||||
.Where(s => s.Date >= from && s.Date <= to)
|
||||
.Select(s => (s.Date, _participation.GetBySessionAndStudent(s.Id, studentId)?.Attendance))
|
||||
.ToList();
|
||||
var rate = _attendanceBalance.Calculate(attendance, from, to).AbsenceRatePercent;
|
||||
AbsenceRateDisplay = $"{rate:0.#} % gefehlt";
|
||||
AbsenceRateColorHex = rate >= ReportGradeRow.HighAbsenceThresholdPercent ? "#D64545" : "#8A8A8A";
|
||||
}
|
||||
|
||||
private void BuildWorks(Guid studentId, GroupMembership? membership, DateOnly displayFrom, DateOnly from, DateOnly to)
|
||||
{
|
||||
foreach (var exam in _calculator.Exams.Where(e => e.Date >= displayFrom && e.Date <= to))
|
||||
{
|
||||
if (!ReportGradeCalculator.ExamApplies(exam, membership)) continue;
|
||||
var results = _calculator.ResultsByExam[exam.Id];
|
||||
results.TryGetValue(studentId, out var own);
|
||||
// Nachschreib-, Förder- und Wiederholungsarbeiten betreffen nur einzelne Schüler — ohne eigenes
|
||||
// Ergebnis gehören sie nicht in diese Übersicht.
|
||||
if (own is null && exam.RepeatOfExamId.HasValue) continue;
|
||||
|
||||
var gradeDisplay = own switch
|
||||
{
|
||||
null => "–",
|
||||
{ Absent: true } => "abw.",
|
||||
_ => own.Grade ?? "–",
|
||||
};
|
||||
|
||||
var percentDisplay = "";
|
||||
if (own is { Absent: false })
|
||||
{
|
||||
var maximum = ExamScoringService.Maximum(exam.Tasks, own.Variant);
|
||||
if (maximum > 0) percentDisplay = $"{own.TotalPoints / maximum * 100:0} %";
|
||||
}
|
||||
|
||||
var classGrades = results.Values.Where(r => !r.Absent && r.Grade is not null)
|
||||
.Select(r => (r.Grade!, 1.0)).ToList();
|
||||
var classAverage = classGrades.Count > 0 ? $"Ø Kurs {Format(_grading.WeightedAverage(classGrades))}" : "";
|
||||
|
||||
var kind = exam.Kind.Label();
|
||||
if (exam.IsSupportWork) kind += " · Förderarbeit";
|
||||
else if (exam.IsMakeUp) kind += " · Nachschreibarbeit";
|
||||
else if (exam.RepeatOfExamId.HasValue) kind += " · Wiederholung";
|
||||
|
||||
Works.Add(new AssistantWorkCard(exam.Title, exam.Date, kind, gradeDisplay, percentDisplay,
|
||||
classAverage, isContext: exam.Date < from));
|
||||
}
|
||||
}
|
||||
|
||||
private void BuildGradeRows(Guid studentId, GroupMembership? membership, DateOnly displayFrom, DateOnly from, DateOnly to)
|
||||
{
|
||||
foreach (var grade in _calculator.Grades
|
||||
.Where(g => g.StudentId == studentId && g.Date >= displayFrom && g.Date <= to)
|
||||
.Where(g => membership is null || GroupMembershipService.IsActiveOn(membership, g.Date)))
|
||||
{
|
||||
var isParticipation = grade.Category == GradeCategory.Participation;
|
||||
var category = GradeCategoryDisplay.Label(grade.Category);
|
||||
var label = string.IsNullOrWhiteSpace(grade.Note)
|
||||
? category
|
||||
: isParticipation ? grade.Note.Trim() : $"{category}: {grade.Note.Trim()}";
|
||||
var row = new AssistantGradeRow(label, grade.Date, grade.Value, isContext: grade.Date < from);
|
||||
(isParticipation ? ParticipationGrades : OtherGrades).Add(row);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mitarbeitsgraph: Abschnitte / Verlauf ────────────────────────────────
|
||||
|
||||
private sealed record SectionView(WizardSectionGroup Group, string Title);
|
||||
|
||||
private void BuildSections(Guid studentId, DateOnly displayFrom, DateOnly to)
|
||||
{
|
||||
var points = _timeline.BuildPoints(studentId).Where(p => p.Date >= displayFrom && p.Date <= to).ToList();
|
||||
// Notierte Zwischenstände erscheinen als Marker im Verlauf.
|
||||
points.AddRange(_interimGrades.GetByStudentAndGroup(studentId, _groupId)
|
||||
.Where(g => g.Date >= displayFrom && g.Date <= to)
|
||||
.Select(g => new WizardTimelinePoint(g.Date, isExam: true, ratingLabel: "",
|
||||
examLabel: $"Zwischenstand: {g.OverallValue}", hasNote: false,
|
||||
tooltip: $"{g.Date:dd.MM.yyyy} · {g.Occasion} · Zwischenstand {g.OverallValue}")));
|
||||
points = points.OrderBy(p => p.Date).ToList();
|
||||
var sectionGrades = _calculator.Grades
|
||||
.Where(g => g.StudentId == studentId && g.Category == GradeCategory.Participation && g.Note is not null)
|
||||
.ToList();
|
||||
|
||||
var views = new List<SectionView>();
|
||||
foreach (var section in _sections.Where(s => s.EndDate >= displayFrom && s.StartDate <= to))
|
||||
{
|
||||
var group = new WizardSectionGroup(ParticipationTimelineBuilder.BandLabel(section), isOpen: false);
|
||||
foreach (var point in points.Where(p => p.Date >= section.StartDate && p.Date <= section.EndDate))
|
||||
group.Points.Add(point);
|
||||
var grade = sectionGrades.FirstOrDefault(g =>
|
||||
g.Note == ParticipationTimelineBuilder.SectionNotePrefix + section.Label)?.Value;
|
||||
views.Add(new SectionView(group,
|
||||
$"{section.Label} · {section.StartDate:dd.MM.}–{section.EndDate:dd.MM.} · " +
|
||||
(grade is null ? "keine Abschnittsnote" : $"Abschnittsnote {grade}")));
|
||||
}
|
||||
|
||||
// Der laufende Abschnitt endet erst mit dem nächsten Abschluss im Mitarbeits-Assistenten;
|
||||
// bis dahin gibt es nur einen Vorschlag aus den bisherigen Sitzungen.
|
||||
var asOf = _interim?.Date ?? _today;
|
||||
// Ohne jeden abgeschlossenen Abschnitt gehört der ganze Zeitraum zum laufenden — sonst
|
||||
// fielen Arbeiten und Zwischenstände vor der ersten Mitarbeit-Sitzung aus dem Verlauf.
|
||||
var openStart = _sections.Count == 0 ? displayFrom : _timeline.OpenStart(_sections, asOf);
|
||||
if (openStart <= to)
|
||||
{
|
||||
var group = new WizardSectionGroup(ParticipationTimelineBuilder.OpenBandLabel(openStart), isOpen: true);
|
||||
foreach (var point in points.Where(p => p.Date >= openStart))
|
||||
group.Points.Add(point);
|
||||
var end = asOf < to ? asOf : to;
|
||||
var suggestion = _timeline.ComputeSuggestion(studentId, openStart < displayFrom ? displayFrom : openStart, end);
|
||||
views.Add(new SectionView(group,
|
||||
$"Laufender Abschnitt seit {openStart:dd.MM.} · " +
|
||||
(suggestion is null ? "noch kein Vorschlag" : $"vorläufig {suggestion}")));
|
||||
}
|
||||
|
||||
_sectionViews = views;
|
||||
// Beim Schülerwechsel im selben Abschnitt bleiben — so lassen sich Schüler abschnittsweise vergleichen.
|
||||
_sectionIndex = Math.Clamp(_sectionIndex, 0, Math.Max(0, views.Count - 1));
|
||||
ApplyChartMode();
|
||||
}
|
||||
|
||||
private void ApplyChartMode()
|
||||
{
|
||||
if (_sectionViews.Count == 0)
|
||||
{
|
||||
ChartGroups = [];
|
||||
SectionTitle = ""; SectionPosition = "";
|
||||
}
|
||||
else if (IsSectionMode)
|
||||
{
|
||||
var view = _sectionViews[_sectionIndex];
|
||||
ChartGroups = [view.Group];
|
||||
SectionTitle = view.Title;
|
||||
SectionPosition = $"{_sectionIndex + 1} / {_sectionViews.Count}";
|
||||
}
|
||||
else
|
||||
{
|
||||
ChartGroups = _sectionViews.Select(v => v.Group).ToList();
|
||||
SectionTitle = ""; SectionPosition = "";
|
||||
}
|
||||
PreviousSectionCommand.NotifyCanExecuteChanged();
|
||||
NextSectionCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
private bool CanGoPreviousSection => IsSectionMode && _sectionIndex > 0;
|
||||
private bool CanGoNextSection => IsSectionMode && _sectionIndex < _sectionViews.Count - 1;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanGoPreviousSection))]
|
||||
private void PreviousSection() { _sectionIndex--; ApplyChartMode(); }
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanGoNextSection))]
|
||||
private void NextSection() { _sectionIndex++; ApplyChartMode(); }
|
||||
|
||||
// ── Navigation ───────────────────────────────────────────────────────────
|
||||
|
||||
private int StudentIndex => SelectedStudent is null ? -1 : Students.IndexOf(SelectedStudent);
|
||||
private bool CanGoPreviousStudent => StudentIndex > 0;
|
||||
private bool CanGoNextStudent => StudentIndex >= 0 && StudentIndex < Students.Count - 1;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanGoPreviousStudent))]
|
||||
private void PreviousStudent() => SelectedStudent = Students[StudentIndex - 1];
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanGoNextStudent))]
|
||||
private void NextStudent() => SelectedStudent = Students[StudentIndex + 1];
|
||||
|
||||
// ── Speichern / Festschreiben ────────────────────────────────────────────
|
||||
|
||||
[RelayCommand]
|
||||
private void Save() => TrySave();
|
||||
|
||||
[RelayCommand]
|
||||
private void SaveAndNext()
|
||||
{
|
||||
if (!TrySave()) return;
|
||||
if (CanGoNextStudent) NextStudent();
|
||||
}
|
||||
|
||||
private bool TrySave()
|
||||
{
|
||||
if (SelectedStudent is null || IsLocked) return false;
|
||||
ClearErrors();
|
||||
var valid = true;
|
||||
if (!string.IsNullOrWhiteSpace(OverrideValue) && string.IsNullOrWhiteSpace(OverrideReason))
|
||||
{
|
||||
OverrideReasonError = "Für ein manuelles Übersteuern ist eine Begründung Pflicht.";
|
||||
valid = false;
|
||||
}
|
||||
if (CanEnterExamGrades)
|
||||
{
|
||||
if (!IsGradeOrEmpty(ProjectExamGrade)) { ProjectExamGradeError = "Keine gültige Note."; valid = false; }
|
||||
if (!IsGradeOrEmpty(OralExamGrade)) { OralExamGradeError = "Keine gültige Note."; valid = false; }
|
||||
if (!IsGradeOrEmpty(WrittenExamGrade)) { WrittenExamGradeError = "Keine gültige Note."; valid = false; }
|
||||
if (!IsGradeOrEmpty(AdditionalOralExamGrade)) { AdditionalOralExamGradeError = "Keine gültige Note."; valid = false; }
|
||||
|
||||
// Ein Fach ist entweder schriftliches oder mündliches Prüfungsfach; eine zusätzliche
|
||||
// mündliche Prüfung gibt es nur im schriftlichen Prüfungsfach oder ganz ohne Abschlussprüfung.
|
||||
var hasOral = NullIfEmpty(OralExamGrade) is not null;
|
||||
if (hasOral && NullIfEmpty(WrittenExamGrade) is not null)
|
||||
{
|
||||
OralExamGradeError = "Entweder schriftliche oder mündliche Abschlussprüfung.";
|
||||
valid = false;
|
||||
}
|
||||
if (hasOral && NullIfEmpty(AdditionalOralExamGrade) is not null)
|
||||
{
|
||||
AdditionalOralExamGradeError = "Im Fach der mündlichen Abschlussprüfung nicht vorgesehen.";
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
if (!valid) return false;
|
||||
|
||||
var record = _reportGrades.GetByStudentGroupPeriod(SelectedStudent.StudentId, _groupId, SelectedPeriod.Label)
|
||||
?? new ReportGrade { StudentId = SelectedStudent.StudentId, GroupId = _groupId, Period = SelectedPeriod.Label };
|
||||
record.CalculatedValue = _calculatedValue ?? "";
|
||||
record.OverrideValue = NullIfEmpty(OverrideValue);
|
||||
record.OverrideReason = NullIfEmpty(OverrideReason);
|
||||
if (CanEnterExamGrades)
|
||||
{
|
||||
record.ProjectExamGrade = NullIfEmpty(ProjectExamGrade);
|
||||
record.OralExamGrade = NullIfEmpty(OralExamGrade);
|
||||
record.WrittenExamGrade = NullIfEmpty(WrittenExamGrade);
|
||||
record.AdditionalOralExamGrade = NullIfEmpty(AdditionalOralExamGrade);
|
||||
}
|
||||
record.UpdatedAt = DateTime.UtcNow;
|
||||
_reportGrades.Save(record);
|
||||
|
||||
RefreshItem(SelectedStudent);
|
||||
StatusMessage = "Gespeichert.";
|
||||
return true;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ToggleLock()
|
||||
{
|
||||
if (SelectedStudent is null) return;
|
||||
var studentId = SelectedStudent.StudentId;
|
||||
var record = _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, SelectedPeriod.Label);
|
||||
if (!IsLocked)
|
||||
{
|
||||
// Festschreiben sichert immer zuerst den aktuell angezeigten Stand.
|
||||
if (!TrySave()) return;
|
||||
record = _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, SelectedPeriod.Label);
|
||||
}
|
||||
if (record is null) return;
|
||||
|
||||
record.IsLocked = !record.IsLocked;
|
||||
record.UpdatedAt = DateTime.UtcNow;
|
||||
_reportGrades.Save(record);
|
||||
RefreshItem(SelectedStudent);
|
||||
ShowStudent();
|
||||
StatusMessage = record.IsLocked ? "Festgeschrieben." : "Entsperrt.";
|
||||
}
|
||||
|
||||
private static string? NullIfEmpty(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
|
||||
/// Ganze Note bzw. Punktzahl, optional mit Tendenz ("3+", "2-") — dieselbe Schreibweise, die
|
||||
/// die Notenberechnung versteht; alles andere würde dort stillschweigend ausgelassen.
|
||||
private static bool IsGradeOrEmpty(string? value)
|
||||
{
|
||||
var text = NullIfEmpty(value);
|
||||
return text is null || int.TryParse(text.TrimEnd('+', '-').TrimEnd(), out _);
|
||||
}
|
||||
|
||||
private static string Format(double value) => value.ToString("0.00", German);
|
||||
}
|
||||
|
||||
// ── Bausteine ────────────────────────────────────────────────────────────────
|
||||
|
||||
public enum AssistantGradeStatus { Open, Saved, Locked, Noted }
|
||||
|
||||
public partial class AssistantStudentItem(Guid studentId, string name) : ObservableObject
|
||||
{
|
||||
public Guid StudentId { get; } = studentId;
|
||||
public string Name { get; } = name;
|
||||
|
||||
[ObservableProperty] private string _gradeDisplay = "–";
|
||||
[ObservableProperty] private AssistantGradeStatus _status;
|
||||
|
||||
public string StatusLabel => Status switch
|
||||
{
|
||||
AssistantGradeStatus.Locked => "festgeschrieben",
|
||||
AssistantGradeStatus.Saved => "gespeichert",
|
||||
AssistantGradeStatus.Noted => "notiert",
|
||||
_ => "offen",
|
||||
};
|
||||
|
||||
public string StatusColorHex => Status switch
|
||||
{
|
||||
AssistantGradeStatus.Locked => "#2E9D57",
|
||||
AssistantGradeStatus.Saved or AssistantGradeStatus.Noted => "#2E86DE",
|
||||
_ => "#8A8A8A",
|
||||
};
|
||||
|
||||
public void Update(string gradeDisplay, AssistantGradeStatus status)
|
||||
{
|
||||
GradeDisplay = gradeDisplay;
|
||||
Status = status;
|
||||
}
|
||||
|
||||
partial void OnStatusChanged(AssistantGradeStatus value)
|
||||
{
|
||||
OnPropertyChanged(nameof(StatusLabel));
|
||||
OnPropertyChanged(nameof(StatusColorHex));
|
||||
}
|
||||
}
|
||||
|
||||
public class AssistantTile(string label, string value, string hint)
|
||||
{
|
||||
public string Label { get; } = label;
|
||||
public string Value { get; } = value;
|
||||
public string Hint { get; } = hint;
|
||||
}
|
||||
|
||||
public class AssistantWorkCard(string title, DateOnly date, string kindLabel, string gradeDisplay,
|
||||
string percentDisplay, string classAverageDisplay, bool isContext)
|
||||
{
|
||||
public string Title { get; } = title;
|
||||
public string DateDisplay { get; } = date.ToString("dd.MM.yyyy");
|
||||
public string KindLabel { get; } = kindLabel;
|
||||
public string GradeDisplay { get; } = gradeDisplay;
|
||||
public string PercentDisplay { get; } = percentDisplay;
|
||||
public string ClassAverageDisplay { get; } = classAverageDisplay;
|
||||
/// Vorhalbjahr: nur zum Vergleich gezeigt, zählt nicht in die aktuelle Note.
|
||||
public bool IsContext { get; } = isContext;
|
||||
public double DisplayOpacity => IsContext ? 0.45 : 1.0;
|
||||
public string ContextLabel => IsContext ? "1. Halbjahr · zählt nicht" : "";
|
||||
}
|
||||
|
||||
public class AssistantGradeRow(string label, DateOnly date, string value, bool isContext)
|
||||
{
|
||||
public string Label { get; } = label;
|
||||
public string DateDisplay { get; } = date.ToString("dd.MM.yyyy");
|
||||
public string Value { get; } = value;
|
||||
public bool IsContext { get; } = isContext;
|
||||
public double DisplayOpacity => IsContext ? 0.45 : 1.0;
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
|
||||
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||
|
||||
public sealed record ReportGradeResult(double? Value, string? Rounded, double? Written, double? Participation, double? Other);
|
||||
|
||||
/// Eine Teilnote der Endjahresnote: Halbjahresnote oder Prüfungsleistung.
|
||||
/// <param name="Value">Rechenwert, wenn er sich nicht aus <paramref name="Final"/> ergibt —
|
||||
/// etwa eine Prüfungsleistung, die zwischen zwei Noten liegt.</param>
|
||||
public sealed record YearPart(string Label, string? Final, string Hint, double Weight = 1.0, double? Value = null);
|
||||
|
||||
/// Prüfungsnoten der Klasse 10, soweit in diesem Fach abgelegt.
|
||||
public readonly record struct YearExamGrades(string? Project, string? Oral,
|
||||
string? Written = null, string? AdditionalOral = null);
|
||||
|
||||
/// <summary>
|
||||
/// Gemeinsame Zeugnisnoten-Berechnung für Zeugnisnoten-Dialog (2.4) und Zeugnisnoten-Assistent
|
||||
/// (2.7), damit beide für denselben Datensatz denselben Wert zeigen.
|
||||
///
|
||||
/// Halbjahre sind eigenständig und werden aus den Einzelleistungen ihres Zeitraums gewichtet.
|
||||
/// Die Endjahresnote wird dagegen aus den Halbjahresnoten verrechnet (gleich gewichtet).
|
||||
///
|
||||
/// Klasse 10 (Bremen): In einem Prüfungsfach ergibt sich die Gesamtnote zu zwei Dritteln aus der
|
||||
/// unterrichtlichen Leistung und zu einem Drittel aus der Prüfungsleistung (§ 14 Abs. 3 der
|
||||
/// Verordnung über die Sekundarstufe I der Oberschule) — die Prüfung zählt also wie ein drittes
|
||||
/// Halbjahr. Die Prüfungsleistung ist die Note der schriftlichen bzw. mündlichen
|
||||
/// Abschlussprüfung. Kommt in einem schriftlichen Prüfungsfach eine zusätzliche mündliche
|
||||
/// Prüfung hinzu, werden beide 1:1 verrechnet (§ 13 Abs. 2 PrüfV Sek. I). In einem Fach ohne
|
||||
/// Abschlussprüfung zählt eine zusätzliche mündliche Prüfung selbst als Prüfungsleistung, also
|
||||
/// 2:1 (§ 13 Abs. 3 PrüfV Sek. I). Die Projektprüfung zählt nach Schulpraxis als weiteres
|
||||
/// Halbjahr.
|
||||
///
|
||||
/// Bewusst nicht umgesetzt sind die Rundungsvorgaben der Verordnungen: Noten sind
|
||||
/// Leistungsbewertungen, die Entscheidung zwischen zwei Noten ist pädagogisch. Eine
|
||||
/// Prüfungsleistung zwischen zwei Noten geht deshalb ungerundet in die Rechnung ein, und für die
|
||||
/// Endnote gilt die von der Lehrkraft gewählte Rundung samt Möglichkeit zum Übersteuern.
|
||||
/// </summary>
|
||||
public sealed class ReportGradeCalculator
|
||||
{
|
||||
public const string ProjectExamLabel = "Projektprüfung";
|
||||
public const string OralExamLabel = "Mündliche Prüfung";
|
||||
public const string WrittenExamLabel = "Schriftliche Prüfung";
|
||||
public const string AdditionalOralExamLabel = "Zusätzliche mündliche Prüfung";
|
||||
|
||||
private readonly IGradeRepository _grades;
|
||||
private readonly IExamRepository _exams;
|
||||
private readonly IExamResultRepository _results;
|
||||
private readonly IGradingSchemeRepository _schemes;
|
||||
private readonly IReportGradeRepository _reportGrades;
|
||||
private readonly IReadOnlyDictionary<Guid, GroupMembership> _membershipsByStudent;
|
||||
private readonly GradingService _grading;
|
||||
private readonly Guid _groupId;
|
||||
private readonly GroupType _groupType;
|
||||
private readonly GradingSystem _gradingSystem;
|
||||
private readonly string _schoolYear;
|
||||
|
||||
public GradingScheme Scheme { get; private set; } = new();
|
||||
public List<Exam> Exams { get; private set; } = [];
|
||||
public Dictionary<Guid, Dictionary<Guid, ExamResult>> ResultsByExam { get; private set; } = [];
|
||||
public List<Grade> Grades { get; private set; } = [];
|
||||
|
||||
public string SchemeSummary =>
|
||||
$"Klausuren {Scheme.ExamsPercent:0.#} % · Mitarbeit {Scheme.ParticipationPercent:0.#} % · " +
|
||||
$"Sonstige {Scheme.OtherPercent:0.#} %";
|
||||
|
||||
public ReportGradeCalculator(IGradeRepository grades, IExamRepository exams, IExamResultRepository results,
|
||||
IGradingSchemeRepository schemes, IReportGradeRepository reportGrades,
|
||||
IReadOnlyDictionary<Guid, GroupMembership> membershipsByStudent, GradingService grading,
|
||||
Guid groupId, GroupType groupType, GradingSystem gradingSystem, string schoolYear)
|
||||
{
|
||||
_grades = grades; _exams = exams; _results = results; _schemes = schemes;
|
||||
_reportGrades = reportGrades; _membershipsByStudent = membershipsByStudent; _grading = grading;
|
||||
_groupId = groupId; _groupType = groupType; _gradingSystem = gradingSystem; _schoolYear = schoolYear;
|
||||
Reload();
|
||||
}
|
||||
|
||||
/// Liest Schema, Arbeiten und Noten neu ein — vor jeder Neuberechnung einer ganzen Ansicht.
|
||||
public void Reload()
|
||||
{
|
||||
Scheme = _schemes.GetByGroup(_groupId)
|
||||
?? _schemes.GetDefaultForType(_groupType)
|
||||
?? new GradingScheme { ExamsPercent = 50, ParticipationPercent = 40, OtherPercent = 10 };
|
||||
Exams = _exams.GetByGroup(_groupId).OrderBy(e => e.Date).ToList();
|
||||
ResultsByExam = Exams.ToDictionary(e => e.Id,
|
||||
e => _results.GetByExam(e.Id).GroupBy(r => r.StudentId).ToDictionary(g => g.Key, g => g.First()));
|
||||
Grades = _grades.GetByGroup(_groupId).OrderBy(g => g.Date).ToList();
|
||||
}
|
||||
|
||||
public (DateOnly From, DateOnly To) Range(ParticipationPeriod period) =>
|
||||
GroupMembershipService.SchoolYearPeriod(_schoolYear, period switch
|
||||
{
|
||||
ParticipationPeriod.H1 => SchoolYearPeriodKind.H1,
|
||||
ParticipationPeriod.H2 => SchoolYearPeriodKind.H2,
|
||||
_ => SchoolYearPeriodKind.FullYear,
|
||||
});
|
||||
|
||||
public static string PeriodLabel(ParticipationPeriod period) => period switch
|
||||
{
|
||||
ParticipationPeriod.H1 => "1. Halbjahr",
|
||||
ParticipationPeriod.H2 => "2. Halbjahr",
|
||||
_ => "Gesamtes Schuljahr",
|
||||
};
|
||||
|
||||
public static bool ExamApplies(Exam exam, GroupMembership? membership)
|
||||
{
|
||||
if (membership is not null && !GroupMembershipService.IsActiveOn(membership, exam.Date)) return false;
|
||||
return !exam.Niveau.HasValue || membership?.Niveau == exam.Niveau;
|
||||
}
|
||||
|
||||
public string Round(double value, RoundingRule rounding) => _grading.RoundToGrade(value, _gradingSystem, rounding);
|
||||
|
||||
/// <param name="examGrades">Noch nicht gespeicherte Prüfungsnoten für die Jahresnote; ohne
|
||||
/// Angabe gelten die am Jahres-Datensatz gespeicherten.</param>
|
||||
/// <param name="asOf">Stichtag für ein Halbjahr: nur Leistungen bis einschließlich dieses
|
||||
/// Tages zählen.</param>
|
||||
/// <param name="runningParticipation">Vorläufige Mitarbeitsnote des laufenden, noch nicht
|
||||
/// abgeschlossenen Abschnitts — zählt für ein Halbjahr wie eine weitere Abschnittsnote.</param>
|
||||
public ReportGradeResult Calculate(Guid studentId, ParticipationPeriod period, RoundingRule rounding,
|
||||
YearExamGrades? examGrades = null, DateOnly? asOf = null, string? runningParticipation = null)
|
||||
{
|
||||
if (period == ParticipationPeriod.FullYear)
|
||||
{
|
||||
var parts = YearParts(studentId, rounding, examGrades)
|
||||
.Select(p => (Value: p.Value ?? (p.Final is null ? null : GradingService.ParseGradeValue(p.Final)), p.Weight))
|
||||
.Where(p => p.Value.HasValue).ToList();
|
||||
if (parts.Count == 0) return new ReportGradeResult(null, null, null, null, null);
|
||||
var mean = parts.Sum(p => p.Value!.Value * p.Weight) / parts.Sum(p => p.Weight);
|
||||
return new ReportGradeResult(mean, _grading.RoundToGrade(mean, _gradingSystem, rounding), null, null, null);
|
||||
}
|
||||
|
||||
var (from, to) = Range(period);
|
||||
if (asOf is { } cutoff && cutoff < to) to = cutoff;
|
||||
_membershipsByStudent.TryGetValue(studentId, out var membership);
|
||||
|
||||
var examEntries = new List<(Exam Exam, string Grade)>();
|
||||
foreach (var exam in Exams.Where(e => e.Date >= from && e.Date <= to))
|
||||
{
|
||||
if (!ExamApplies(exam, membership)) continue;
|
||||
if (!ResultsByExam[exam.Id].TryGetValue(studentId, out var result)) continue;
|
||||
if (result.Absent || result.Grade is null) continue;
|
||||
examEntries.Add((exam, result.Grade));
|
||||
}
|
||||
var (writtenGrades, testGrades) = ExamScoringService.EffectiveGradesByKind(examEntries, _gradingSystem);
|
||||
var written = writtenGrades.Select(grade => (Grade: grade, Weight: 1.0)).ToList();
|
||||
|
||||
var studentGrades = Grades
|
||||
.Where(g => g.StudentId == studentId && g.Date >= from && g.Date <= to)
|
||||
.Where(g => membership is null || GroupMembershipService.IsActiveOn(membership, g.Date))
|
||||
.ToList();
|
||||
var participation = studentGrades.Where(g => g.Category == GradeCategory.Participation)
|
||||
.Select(g => (Grade: g.Value, g.Weight)).ToList();
|
||||
if (!string.IsNullOrWhiteSpace(runningParticipation)) participation.Add((runningParticipation, 1.0));
|
||||
var other = studentGrades.Where(g => g.Category != GradeCategory.Participation)
|
||||
.Select(g => (Grade: g.Value, g.Weight)).ToList();
|
||||
// Tests, kontrollierte Hausaufgaben u. Ä. aus der Klausurfunktion zählen als Sonstige.
|
||||
other.AddRange(testGrades.Select(grade => (Grade: grade, Weight: 1.0)));
|
||||
|
||||
var value = _grading.CalculateReportGradeValue(written, participation, other, Scheme);
|
||||
return new ReportGradeResult(value,
|
||||
value is null ? null : _grading.RoundToGrade(value.Value, _gradingSystem, rounding),
|
||||
written.Count > 0 ? _grading.WeightedAverage(written) : null,
|
||||
participation.Count > 0 ? _grading.WeightedAverage(participation) : null,
|
||||
other.Count > 0 ? _grading.WeightedAverage(other) : null);
|
||||
}
|
||||
|
||||
/// Die Teilnoten der Endjahresnote. Bei den Halbjahren geht eine gespeicherte Entscheidung
|
||||
/// (Übersteuerung bzw. festgeschriebener Wert) der Live-Berechnung vor.
|
||||
public List<YearPart> YearParts(Guid studentId, RoundingRule rounding, YearExamGrades? examGrades = null)
|
||||
{
|
||||
var parts = new List<YearPart>();
|
||||
foreach (var half in new[] { ParticipationPeriod.H1, ParticipationPeriod.H2 })
|
||||
{
|
||||
var label = PeriodLabel(half);
|
||||
var record = _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, label);
|
||||
var overridden = NullIfEmpty(record?.OverrideValue);
|
||||
if (overridden is not null)
|
||||
parts.Add(new YearPart(label, overridden, record!.IsLocked ? "festgeschrieben" : "übersteuert"));
|
||||
else if (record is { IsLocked: true })
|
||||
parts.Add(new YearPart(label, NullIfEmpty(record.CalculatedValue), "festgeschrieben"));
|
||||
else
|
||||
parts.Add(new YearPart(label, Calculate(studentId, half, rounding).Rounded, "berechnet"));
|
||||
}
|
||||
|
||||
// Die unterrichtliche Leistung zählt immer doppelt gegenüber einer Prüfung — auch wenn
|
||||
// nur eine der beiden Halbjahresnoten vorliegt.
|
||||
if (parts.Count(p => p.Final is not null) == 1)
|
||||
parts = parts.Select(p => p.Final is null ? p : p with { Weight = 2.0 }).ToList();
|
||||
|
||||
var exams = examGrades ?? StoredExamGrades(studentId);
|
||||
if (NullIfEmpty(exams.Project) is { } project)
|
||||
parts.Add(new YearPart(ProjectExamLabel, project, "zählt wie ein Halbjahr"));
|
||||
if (ExamPerformance(exams) is { } performance)
|
||||
parts.Add(performance);
|
||||
return parts;
|
||||
}
|
||||
|
||||
/// Die Prüfungsleistung des Fachs, die mit einem Drittel in die Gesamtnote eingeht.
|
||||
private YearPart? ExamPerformance(YearExamGrades exams)
|
||||
{
|
||||
var written = NullIfEmpty(exams.Written);
|
||||
var oral = NullIfEmpty(exams.Oral);
|
||||
var additional = NullIfEmpty(exams.AdditionalOral);
|
||||
|
||||
if (written is not null && additional is not null)
|
||||
{
|
||||
// § 13 Abs. 2 PrüfV Sek. I: 1:1. Liegt das Ergebnis zwischen zwei Noten, wird hier
|
||||
// nicht gerundet — es geht so in die Endnote ein, entschieden wird dort.
|
||||
var mean = _grading.WeightedAverage([(written, 1.0), (additional, 1.0)]);
|
||||
var between = BetweenGrades(mean);
|
||||
return new YearPart("Prüfungsleistung", mean.ToString("0.##", German),
|
||||
$"schriftlich {written} · mündlich {additional}" + (between is null ? "" : $" — {between}"),
|
||||
Value: mean);
|
||||
}
|
||||
if (written is not null) return new YearPart(WrittenExamLabel, written, "ein Drittel der Note");
|
||||
if (oral is not null) return new YearPart(OralExamLabel, oral, "ein Drittel der Note");
|
||||
if (additional is not null) return new YearPart(AdditionalOralExamLabel, additional, "ein Drittel der Note");
|
||||
return null;
|
||||
}
|
||||
|
||||
public YearExamGrades StoredExamGrades(Guid studentId)
|
||||
{
|
||||
var year = _reportGrades.GetByStudentGroupPeriod(studentId, _groupId, PeriodLabel(ParticipationPeriod.FullYear));
|
||||
return new YearExamGrades(year?.ProjectExamGrade, year?.OralExamGrade,
|
||||
year?.WrittenExamGrade, year?.AdditionalOralExamGrade);
|
||||
}
|
||||
|
||||
/// "zwischen 4 und 5", wenn der Wert genau auf der Grenze zweier Noten liegt — dann gibt
|
||||
/// es rechnerisch keine richtige Seite, nur eine pädagogische Entscheidung.
|
||||
public static string? BetweenGrades(double value)
|
||||
{
|
||||
var lower = Math.Floor(value);
|
||||
return Math.Abs(value - lower - 0.5) < 0.0001 ? $"zwischen {lower:0} und {lower + 1:0}" : null;
|
||||
}
|
||||
|
||||
private static readonly System.Globalization.CultureInfo German =
|
||||
System.Globalization.CultureInfo.GetCultureInfo("de-DE");
|
||||
|
||||
private static string? NullIfEmpty(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
@@ -13,22 +13,15 @@ namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||
|
||||
public partial class ReportGradeDialogViewModel : ObservableObject
|
||||
{
|
||||
private readonly IGradeRepository _grades;
|
||||
private readonly IExamRepository _exams;
|
||||
private readonly IExamResultRepository _results;
|
||||
private readonly IStudentRepository _students;
|
||||
private readonly IGroupMembershipRepository _memberships;
|
||||
private readonly IGradingSchemeRepository _schemes;
|
||||
private readonly IReportGradeRepository _reportGrades;
|
||||
private readonly ReportGradeCalculator _calculator;
|
||||
private readonly IParticipationSessionRepository _participationSessions;
|
||||
private readonly IParticipationRepository _participation;
|
||||
private readonly AttendanceBalanceService _attendanceBalance;
|
||||
private readonly GradingService _grading;
|
||||
private readonly Guid _groupId;
|
||||
private readonly GroupType _groupType;
|
||||
private readonly GradingSystem _gradingSystem;
|
||||
private readonly string _groupLabel;
|
||||
private readonly string _schoolYear;
|
||||
|
||||
[ObservableProperty] private ParticipationPeriodOption _selectedPeriod;
|
||||
[ObservableProperty] private RoundingRule _roundingRule = RoundingRule.Commercial;
|
||||
@@ -59,12 +52,13 @@ public partial class ReportGradeDialogViewModel : ObservableObject
|
||||
AttendanceBalanceService attendanceBalance, GradingService grading,
|
||||
Guid groupId, GroupType groupType, GradingSystem gradingSystem, string groupLabel, string schoolYear)
|
||||
{
|
||||
_grades = grades; _exams = exams; _results = results; _students = students;
|
||||
_memberships = memberships; _schemes = schemes; _reportGrades = reportGrades; _grading = grading;
|
||||
_students = students; _memberships = memberships; _reportGrades = reportGrades;
|
||||
_participationSessions = participationSessions; _participation = participation;
|
||||
_attendanceBalance = attendanceBalance;
|
||||
_groupId = groupId; _groupType = groupType; _gradingSystem = gradingSystem; _groupLabel = groupLabel;
|
||||
_schoolYear = schoolYear;
|
||||
_groupId = groupId; _groupLabel = groupLabel;
|
||||
_calculator = new ReportGradeCalculator(grades, exams, results, schemes, reportGrades,
|
||||
memberships.GetByGroup(groupId).ToDictionary(m => m.StudentId), grading,
|
||||
groupId, groupType, gradingSystem, schoolYear);
|
||||
|
||||
_selectedPeriod = PeriodOptions[0];
|
||||
Recompute();
|
||||
@@ -73,31 +67,19 @@ public partial class ReportGradeDialogViewModel : ObservableObject
|
||||
partial void OnSelectedPeriodChanged(ParticipationPeriodOption value) => Recompute();
|
||||
partial void OnRoundingRuleChanged(RoundingRule value) => Recompute();
|
||||
|
||||
private GradingScheme ResolveScheme() =>
|
||||
_schemes.GetByGroup(_groupId)
|
||||
?? _schemes.GetDefaultForType(_groupType)
|
||||
?? new GradingScheme { ExamsPercent = 50, ParticipationPercent = 40, OtherPercent = 10 };
|
||||
public void Refresh() => Recompute();
|
||||
|
||||
private void Recompute()
|
||||
{
|
||||
var scheme = ResolveScheme();
|
||||
SchemeSummary = $"Klausuren {scheme.ExamsPercent:0.#} % · Mitarbeit {scheme.ParticipationPercent:0.#} % · " +
|
||||
$"Sonstige {scheme.OtherPercent:0.#} %";
|
||||
_calculator.Reload();
|
||||
SchemeSummary = _calculator.SchemeSummary;
|
||||
|
||||
var period = SelectedPeriod.Period;
|
||||
var periodTag = SelectedPeriod.Label;
|
||||
var (periodFrom, periodTo) = GroupMembershipService.SchoolYearPeriod(_schoolYear, period switch
|
||||
{
|
||||
ParticipationPeriod.H1 => SchoolYearPeriodKind.H1,
|
||||
ParticipationPeriod.H2 => SchoolYearPeriodKind.H2,
|
||||
_ => SchoolYearPeriodKind.FullYear,
|
||||
});
|
||||
var (periodFrom, periodTo) = _calculator.Range(period);
|
||||
|
||||
var students = _students.GetByGroup(_groupId);
|
||||
var membershipsByStudent = _memberships.GetByGroup(_groupId).ToDictionary(m => m.StudentId);
|
||||
var exams = _exams.GetByGroup(_groupId).Where(e => e.Date >= periodFrom && e.Date <= periodTo).ToList();
|
||||
var resultsByExam = exams.ToDictionary(e => e.Id, e => _results.GetByExam(e.Id).ToDictionary(r => r.StudentId));
|
||||
var allGrades = _grades.GetByGroup(_groupId).Where(g => g.Date >= periodFrom && g.Date <= periodTo).ToList();
|
||||
|
||||
// Fehlquote (Nutzer-Feedback): je Schüler die Anwesenheits-Bilanz im gewählten Zeitraum,
|
||||
// nur aus Sitzungen dieser Gruppe (anders als StudentDetailViewModel.LoadAttendanceBalance,
|
||||
@@ -132,29 +114,9 @@ public partial class ReportGradeDialogViewModel : ObservableObject
|
||||
continue;
|
||||
}
|
||||
|
||||
var examEntries = new List<(Exam Exam, string Grade)>();
|
||||
foreach (var exam in exams)
|
||||
{
|
||||
if (membership is not null && !GroupMembershipService.IsActiveOn(membership, exam.Date)) continue;
|
||||
if (exam.Niveau.HasValue && membership?.Niveau != exam.Niveau) continue;
|
||||
if (!resultsByExam[exam.Id].TryGetValue(student.Id, out var result)) continue;
|
||||
if (result.Absent || result.Grade is null) continue;
|
||||
examEntries.Add((exam, result.Grade));
|
||||
}
|
||||
var examGrades = ExamScoringService.EffectiveGrades(examEntries, _gradingSystem)
|
||||
.Select(grade => (Grade: grade, Weight: 1.0)).ToList();
|
||||
|
||||
var participationGrades = allGrades
|
||||
.Where(g => g.StudentId == student.Id && g.Category == GradeCategory.Participation
|
||||
&& (membership is null || GroupMembershipService.IsActiveOn(membership, g.Date)))
|
||||
.Select(g => (g.Value, g.Weight)).ToList();
|
||||
var otherGrades = allGrades
|
||||
.Where(g => g.StudentId == student.Id && g.Category != GradeCategory.Participation
|
||||
&& (membership is null || GroupMembershipService.IsActiveOn(membership, g.Date)))
|
||||
.Select(g => (g.Value, g.Weight)).ToList();
|
||||
|
||||
var calculated = _grading.CalculateReportGrade(examGrades, participationGrades, otherGrades,
|
||||
scheme, _gradingSystem, RoundingRule);
|
||||
// Halbjahre aus den Einzelleistungen, das Schuljahr aus den Halbjahresnoten
|
||||
// (plus ggf. Prüfungsnoten) — siehe ReportGradeCalculator.
|
||||
var calculated = _calculator.Calculate(student.Id, period, RoundingRule).Rounded;
|
||||
|
||||
Rows.Add(ReportGradeRow.FromCalculated(student.Id, student.FullName, calculated, existing, absenceRate, Save, ToggleLock));
|
||||
}
|
||||
|
||||
@@ -313,7 +313,8 @@ public partial class SeatingPlanTabViewModel : ObservableObject
|
||||
}
|
||||
entries.TryGetValue(studentId, out var entry);
|
||||
var tags = _documentation?.GetByStudent(studentId)
|
||||
.FirstOrDefault(d => d.IsDraft && d.ParticipationSessionId == SelectedSession.Id)?.Tags ?? [];
|
||||
.FirstOrDefault(d => d.IsDraft && d.StudentId == studentId && d.ParticipationSessionId == SelectedSession.Id)
|
||||
?.Tags ?? [];
|
||||
seat.SetLessonData(entry, tags);
|
||||
}
|
||||
}
|
||||
@@ -340,8 +341,10 @@ public partial class SeatingPlanTabViewModel : ObservableObject
|
||||
seat.SelectedOption.StudentId is not Guid studentId) return;
|
||||
var session = EnsureTodaySession();
|
||||
if (session is null) return;
|
||||
// Nur Entwürfe mit dieser Person als Hauptperson — ein gemeinsamer Eintrag (weitere Beteiligte)
|
||||
// ist keine persönliche Sitzplan-Notiz.
|
||||
var draft = _documentation.GetByStudent(studentId)
|
||||
.FirstOrDefault(d => d.IsDraft && d.ParticipationSessionId == session.Id);
|
||||
.FirstOrDefault(d => d.IsDraft && d.StudentId == studentId && d.ParticipationSessionId == session.Id);
|
||||
if (draft is null)
|
||||
{
|
||||
draft = new Documentation
|
||||
|
||||
@@ -0,0 +1,635 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
namespace LehrerApp.Desktop.ViewModels.Groups;
|
||||
|
||||
public sealed record StudentGroupMember(Guid Id, string Name);
|
||||
public sealed record StudentPairCandidate(Guid Id, string Name);
|
||||
|
||||
public sealed class StudentPairRule
|
||||
{
|
||||
public Guid FirstId { get; }
|
||||
public Guid SecondId { get; }
|
||||
public string Display { get; }
|
||||
public IRelayCommand RemoveCommand { get; }
|
||||
|
||||
public StudentPairRule(StudentPairCandidate first, StudentPairCandidate second, Action<StudentPairRule> remove)
|
||||
{
|
||||
FirstId = first.Id;
|
||||
SecondId = second.Id;
|
||||
Display = $"{first.Name} + {second.Name}";
|
||||
RemoveCommand = new RelayCommand(() => remove(this));
|
||||
}
|
||||
|
||||
public bool Matches(Guid first, Guid second) =>
|
||||
FirstId == first && SecondId == second || FirstId == second && SecondId == first;
|
||||
}
|
||||
|
||||
public sealed partial class GeneratedStudentGroup : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private bool _isDropTarget;
|
||||
public string Title { get; }
|
||||
public ObservableCollection<StudentGroupMember> Members { get; } = [];
|
||||
|
||||
public GeneratedStudentGroup(int number, IEnumerable<Student> students)
|
||||
{
|
||||
Title = $"Gruppe {number}";
|
||||
foreach (var student in students.OrderBy(s => s.LastName, StringComparer.CurrentCultureIgnoreCase)
|
||||
.ThenBy(s => s.FirstName, StringComparer.CurrentCultureIgnoreCase))
|
||||
Members.Add(new StudentGroupMember(student.Id, student.FullName));
|
||||
}
|
||||
|
||||
public GeneratedStudentGroup(int number, IEnumerable<StudentGroupMember> members)
|
||||
{
|
||||
Title = $"Gruppe {number}";
|
||||
foreach (var member in members) Members.Add(member);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Erzeugt Gruppen fuer eine spaetere Planung oder aus der heutigen Anwesenheit.</summary>
|
||||
public partial class StudentGroupGeneratorViewModel : ObservableObject
|
||||
{
|
||||
public const string FutureModeLabel = "Für später · alle Aktiven";
|
||||
public const string AdHocModeLabel = "Ad hoc · heute Anwesende";
|
||||
|
||||
private readonly IStudentRepository _students;
|
||||
private readonly IGroupMembershipRepository _memberships;
|
||||
private readonly IParticipationSessionRepository _sessions;
|
||||
private readonly IParticipationRepository _participation;
|
||||
private readonly IGradeRepository _grades;
|
||||
private readonly IGroupRepository _groupRepository;
|
||||
private readonly IStudentGroupPlanRepository? _savedPlans;
|
||||
private readonly Random _random;
|
||||
private readonly List<Student> _participants = [];
|
||||
private readonly Dictionary<Guid, double?> _performance = [];
|
||||
private readonly HashSet<Guid> _supportStudentIds = [];
|
||||
private Guid? _editingPlanId;
|
||||
private string _attendanceWarning = "";
|
||||
|
||||
[ObservableProperty] private StudentDrawGroup? _selectedGroup;
|
||||
[ObservableProperty] private string _participantModeName = FutureModeLabel;
|
||||
[ObservableProperty] private int _targetGroupSize = 4;
|
||||
[ObservableProperty] private int _targetGroupCount = 6;
|
||||
[ObservableProperty] private double _sizePriority = 75;
|
||||
[ObservableProperty] private double _countPriority = 50;
|
||||
[ObservableProperty] private double _performanceDistribution = 65;
|
||||
[ObservableProperty] private bool _distributeSupportStudents = true;
|
||||
[ObservableProperty] private StudentPairCandidate? _selectedPairStudentA;
|
||||
[ObservableProperty] private StudentPairCandidate? _selectedPairStudentB;
|
||||
[ObservableProperty] private double _forcedPairPriority = 85;
|
||||
[ObservableProperty] private double _excludedPairPriority = 85;
|
||||
[ObservableProperty] private string _pairingMessage = "";
|
||||
[ObservableProperty] private string _statusText = "Optionen wählen und Gruppen zusammenstellen.";
|
||||
[ObservableProperty] private string _warningText = "";
|
||||
[ObservableProperty] private bool _hasGeneratedGroups;
|
||||
[ObservableProperty] private StudentGroupPlan? _selectedSavedPlan;
|
||||
[ObservableProperty] private string _planName = "";
|
||||
[ObservableProperty] private string _saveStatus = "";
|
||||
[ObservableProperty] private bool _hasUnsavedChanges;
|
||||
|
||||
public ObservableCollection<StudentDrawGroup> Groups { get; } = [];
|
||||
public ObservableCollection<GeneratedStudentGroup> GeneratedGroups { get; } = [];
|
||||
public ObservableCollection<StudentPairCandidate> PairCandidates { get; } = [];
|
||||
public ObservableCollection<StudentPairRule> ForcedPairs { get; } = [];
|
||||
public ObservableCollection<StudentPairRule> ExcludedPairs { get; } = [];
|
||||
public ObservableCollection<StudentGroupPlan> SavedPlans { get; } = [];
|
||||
public string[] ParticipantModeOptions { get; } = [FutureModeLabel, AdHocModeLabel];
|
||||
public bool CanGenerate => SelectedGroup is not null && _participants.Count >= 2;
|
||||
public bool CanSave => _savedPlans is not null && SelectedGroup is not null &&
|
||||
HasGeneratedGroups && !string.IsNullOrWhiteSpace(PlanName);
|
||||
public bool CanLoadSavedPlan => SelectedSavedPlan is not null;
|
||||
public bool CanDeleteSavedPlan => SelectedSavedPlan is not null;
|
||||
public bool HasSavedPlans => SavedPlans.Count > 0;
|
||||
public string SizePriorityLabel => PriorityLabel(SizePriority);
|
||||
public string CountPriorityLabel => PriorityLabel(CountPriority);
|
||||
public string PerformanceDistributionLabel => PerformanceDistribution switch
|
||||
{
|
||||
<= -70 => "stark homogen",
|
||||
< -20 => "eher homogen",
|
||||
<= 20 => "zufällig gemischt",
|
||||
< 70 => "eher heterogen",
|
||||
_ => "stark heterogen",
|
||||
};
|
||||
public string ForcedPairPriorityLabel => PriorityLabel(ForcedPairPriority);
|
||||
public string ExcludedPairPriorityLabel => PriorityLabel(ExcludedPairPriority);
|
||||
|
||||
public StudentGroupGeneratorViewModel(
|
||||
IStudentRepository students,
|
||||
IGroupRepository groups,
|
||||
IGroupMembershipRepository memberships,
|
||||
IParticipationSessionRepository sessions,
|
||||
IParticipationRepository participation,
|
||||
IGradeRepository grades,
|
||||
Guid? initialGroupId = null,
|
||||
Random? random = null,
|
||||
IStudentGroupPlanRepository? savedPlans = null)
|
||||
{
|
||||
_students = students;
|
||||
_groupRepository = groups;
|
||||
_memberships = memberships;
|
||||
_sessions = sessions;
|
||||
_participation = participation;
|
||||
_grades = grades;
|
||||
_random = random ?? Random.Shared;
|
||||
_savedPlans = savedPlans;
|
||||
|
||||
foreach (var group in groups.GetAll().OrderBy(g => g.Name, StringComparer.CurrentCultureIgnoreCase))
|
||||
Groups.Add(new StudentDrawGroup(group.Id, group.Name));
|
||||
if (initialGroupId is { } requestedId && Groups.All(g => g.Id != requestedId) &&
|
||||
groups.GetById(requestedId) is { } archived)
|
||||
Groups.Add(new StudentDrawGroup(archived.Id, $"{archived.Name} (archiviert)"));
|
||||
SelectedGroup = Groups.FirstOrDefault(g => g.Id == initialGroupId) ?? Groups.FirstOrDefault();
|
||||
}
|
||||
|
||||
partial void OnSelectedGroupChanged(StudentDrawGroup? value)
|
||||
{
|
||||
ForcedPairs.Clear();
|
||||
ExcludedPairs.Clear();
|
||||
ReloadParticipants();
|
||||
ReloadSavedPlans();
|
||||
_editingPlanId = null;
|
||||
PlanName = "";
|
||||
}
|
||||
partial void OnParticipantModeNameChanged(string value) => ReloadParticipants();
|
||||
partial void OnSelectedSavedPlanChanged(StudentGroupPlan? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(CanLoadSavedPlan));
|
||||
OnPropertyChanged(nameof(CanDeleteSavedPlan));
|
||||
LoadSavedPlanCommand.NotifyCanExecuteChanged();
|
||||
DeleteSavedPlanCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
partial void OnPlanNameChanged(string value)
|
||||
{
|
||||
SavePlanCommand.NotifyCanExecuteChanged();
|
||||
if (HasGeneratedGroups) HasUnsavedChanges = true;
|
||||
}
|
||||
partial void OnHasGeneratedGroupsChanged(bool value) => SavePlanCommand.NotifyCanExecuteChanged();
|
||||
partial void OnTargetGroupSizeChanged(int value) => InvalidateResult();
|
||||
partial void OnTargetGroupCountChanged(int value) => InvalidateResult();
|
||||
partial void OnSizePriorityChanged(double value)
|
||||
{
|
||||
OnPropertyChanged(nameof(SizePriorityLabel));
|
||||
InvalidateResult();
|
||||
}
|
||||
partial void OnCountPriorityChanged(double value)
|
||||
{
|
||||
OnPropertyChanged(nameof(CountPriorityLabel));
|
||||
InvalidateResult();
|
||||
}
|
||||
partial void OnPerformanceDistributionChanged(double value)
|
||||
{
|
||||
OnPropertyChanged(nameof(PerformanceDistributionLabel));
|
||||
InvalidateResult();
|
||||
}
|
||||
partial void OnDistributeSupportStudentsChanged(bool value) => InvalidateResult();
|
||||
partial void OnForcedPairPriorityChanged(double value)
|
||||
{
|
||||
OnPropertyChanged(nameof(ForcedPairPriorityLabel));
|
||||
InvalidateResult();
|
||||
}
|
||||
partial void OnExcludedPairPriorityChanged(double value)
|
||||
{
|
||||
OnPropertyChanged(nameof(ExcludedPairPriorityLabel));
|
||||
InvalidateResult();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void AddForcedPair() => AddPairRule(ForcedPairs, ExcludedPairs);
|
||||
|
||||
[RelayCommand]
|
||||
private void AddExcludedPair() => AddPairRule(ExcludedPairs, ForcedPairs);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanGenerate))]
|
||||
private void Generate()
|
||||
{
|
||||
var groupCount = ResolveGroupCount(_participants.Count);
|
||||
var capacities = Enumerable.Range(0, groupCount)
|
||||
.Select(i => _participants.Count / groupCount + (i < _participants.Count % groupCount ? 1 : 0))
|
||||
.ToArray();
|
||||
var assignments = BuildAssignments(capacities);
|
||||
|
||||
GeneratedGroups.Clear();
|
||||
for (var i = 0; i < assignments.Count; i++)
|
||||
GeneratedGroups.Add(new GeneratedStudentGroup(i + 1, assignments[i]));
|
||||
|
||||
HasGeneratedGroups = true;
|
||||
_editingPlanId = null;
|
||||
SelectedSavedPlan = null;
|
||||
PlanName = $"Einteilung {DateTime.Now:dd.MM.yyyy HH:mm:ss}";
|
||||
HasUnsavedChanges = true;
|
||||
SaveStatus = "Noch nicht gespeichert.";
|
||||
StatusText = $"{_participants.Count} Schüler · {groupCount} Gruppen · Größen " +
|
||||
string.Join("/", capacities.Distinct().OrderBy(x => x));
|
||||
UpdateWarning(groupCount, assignments);
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSave))]
|
||||
private void SavePlan()
|
||||
{
|
||||
if (_savedPlans is null || SelectedGroup is null) return;
|
||||
var plan = new StudentGroupPlan
|
||||
{
|
||||
Id = _editingPlanId ?? Guid.NewGuid(),
|
||||
GroupId = SelectedGroup.Id,
|
||||
Name = PlanName,
|
||||
Groups = GeneratedGroups.Select(group => new StudentGroupPlanGroup
|
||||
{
|
||||
StudentIds = group.Members.Select(member => member.Id).ToList(),
|
||||
}).ToList(),
|
||||
};
|
||||
try
|
||||
{
|
||||
_savedPlans.Save(plan);
|
||||
_editingPlanId = plan.Id;
|
||||
ReloadSavedPlans(plan.Id);
|
||||
HasUnsavedChanges = false;
|
||||
SaveStatus = "Einteilung gespeichert.";
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
|
||||
{
|
||||
SaveStatus = ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanLoadSavedPlan))]
|
||||
private void LoadSavedPlan()
|
||||
{
|
||||
if (_savedPlans is null || SelectedSavedPlan is not { } selected ||
|
||||
SelectedGroup?.Id != selected.GroupId) return;
|
||||
var plan = _savedPlans.GetById(selected.Id);
|
||||
if (plan is null) { ReloadSavedPlans(); return; }
|
||||
_editingPlanId = plan.Id;
|
||||
|
||||
var missing = 0;
|
||||
GeneratedGroups.Clear();
|
||||
foreach (var group in plan.Groups ?? [])
|
||||
{
|
||||
var members = new List<StudentGroupMember>();
|
||||
foreach (var id in group.StudentIds ?? [])
|
||||
{
|
||||
if (_students.GetById(id) is { } student)
|
||||
members.Add(new StudentGroupMember(id, student.FullName));
|
||||
else missing++;
|
||||
}
|
||||
GeneratedGroups.Add(new GeneratedStudentGroup(GeneratedGroups.Count + 1, members));
|
||||
}
|
||||
HasGeneratedGroups = GeneratedGroups.Count > 0;
|
||||
PlanName = plan.Name;
|
||||
HasUnsavedChanges = missing > 0;
|
||||
SaveStatus = missing > 0
|
||||
? $"{missing} nicht mehr vorhandene Schüler wurden ausgelassen. Bitte erneut speichern."
|
||||
: "Gespeicherte Einteilung geladen.";
|
||||
StatusText = $"{GeneratedGroups.Sum(group => group.Members.Count)} Schüler · " +
|
||||
$"{GeneratedGroups.Count} Gruppen · gespeichert am {plan.UpdatedAt.ToLocalTime():dd.MM.yyyy}";
|
||||
WarningText = missing > 0 ? SaveStatus : "";
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanDeleteSavedPlan))]
|
||||
private void DeleteSavedPlan()
|
||||
{
|
||||
if (_savedPlans is null || SelectedSavedPlan is not { } plan) return;
|
||||
_savedPlans.Delete(plan.Id);
|
||||
var deletedCurrent = _editingPlanId == plan.Id;
|
||||
if (deletedCurrent) _editingPlanId = null;
|
||||
ReloadSavedPlans();
|
||||
if (deletedCurrent) HasUnsavedChanges = HasGeneratedGroups;
|
||||
SaveStatus = "Gespeicherte Einteilung gelöscht.";
|
||||
}
|
||||
|
||||
public bool MoveStudent(StudentGroupMember member, GeneratedStudentGroup target)
|
||||
{
|
||||
if (!HasGeneratedGroups || !GeneratedGroups.Contains(target)) return false;
|
||||
var source = GeneratedGroups.FirstOrDefault(group => group.Members.Contains(member));
|
||||
if (source is null || source == target || target.Members.Any(m => m.Id == member.Id)) return false;
|
||||
source.Members.Remove(member);
|
||||
target.Members.Add(member);
|
||||
HasUnsavedChanges = true;
|
||||
SaveStatus = "Änderungen noch nicht gespeichert.";
|
||||
StatusText = $"{GeneratedGroups.Sum(group => group.Members.Count)} Schüler · " +
|
||||
$"{GeneratedGroups.Count} Gruppen · manuell angepasst";
|
||||
var assignments = GeneratedGroups.Select(group => group.Members
|
||||
.Select(m => _students.GetById(m.Id)).OfType<Student>().ToList()).ToList();
|
||||
UpdateWarning(GeneratedGroups.Count, assignments);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ReloadSavedPlans(Guid? selectedId = null)
|
||||
{
|
||||
SavedPlans.Clear();
|
||||
SelectedSavedPlan = null;
|
||||
if (_savedPlans is not null && SelectedGroup is not null)
|
||||
{
|
||||
foreach (var plan in _savedPlans.GetByGroup(SelectedGroup.Id)) SavedPlans.Add(plan);
|
||||
SelectedSavedPlan = SavedPlans.FirstOrDefault(plan => plan.Id == selectedId);
|
||||
}
|
||||
OnPropertyChanged(nameof(HasSavedPlans));
|
||||
}
|
||||
|
||||
private void ReloadParticipants()
|
||||
{
|
||||
_participants.Clear();
|
||||
_performance.Clear();
|
||||
_supportStudentIds.Clear();
|
||||
PairCandidates.Clear();
|
||||
_attendanceWarning = "";
|
||||
|
||||
if (SelectedGroup is not null)
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var activeMemberships = _memberships.GetByGroup(SelectedGroup.Id)
|
||||
.Where(m => GroupMembershipService.IsActiveOn(m, today))
|
||||
.ToList();
|
||||
var activeIds = activeMemberships.Select(m => m.StudentId).ToHashSet();
|
||||
foreach (var membership in activeMemberships.Where(m => m.Niveau == Niveau.Foerder))
|
||||
_supportStudentIds.Add(membership.StudentId);
|
||||
var active = _students.GetByGroup(SelectedGroup.Id)
|
||||
.Where(s => s.IsActive && activeIds.Contains(s.Id)).ToList();
|
||||
_participants.AddRange(ParticipantModeName == AdHocModeLabel
|
||||
? FilterByTodayAttendance(SelectedGroup.Id, active, today)
|
||||
: active);
|
||||
LoadPerformance(SelectedGroup.Id);
|
||||
foreach (var student in _participants.OrderBy(s => s.LastName).ThenBy(s => s.FirstName))
|
||||
PairCandidates.Add(new StudentPairCandidate(student.Id, student.FullName));
|
||||
}
|
||||
|
||||
SelectedPairStudentA = null;
|
||||
SelectedPairStudentB = null;
|
||||
|
||||
InvalidateResult();
|
||||
OnPropertyChanged(nameof(CanGenerate));
|
||||
GenerateCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
private IEnumerable<Student> FilterByTodayAttendance(Guid groupId, List<Student> active, DateOnly today)
|
||||
{
|
||||
var todaySessions = _sessions.GetByGroup(groupId).Where(s => s.Date == today)
|
||||
.OrderBy(s => s.CreatedAt).ToList();
|
||||
if (todaySessions.Count == 0)
|
||||
{
|
||||
_attendanceWarning = "Heute wurde noch keine Anwesenheit erfasst; deshalb werden alle aktiven Schüler einbezogen.";
|
||||
return active;
|
||||
}
|
||||
|
||||
var latestStatus = new Dictionary<Guid, AttendanceStatus?>();
|
||||
foreach (var session in todaySessions)
|
||||
foreach (var entry in _participation.GetBySession(session.Id))
|
||||
if (entry.Attendance is not null) latestStatus[entry.StudentId] = entry.Attendance;
|
||||
|
||||
var unknown = active.Count(s => !latestStatus.ContainsKey(s.Id));
|
||||
if (unknown > 0)
|
||||
_attendanceWarning = $"Für {unknown} Schüler fehlt heute ein Anwesenheitsstatus; sie werden vorsichtshalber einbezogen.";
|
||||
return active.Where(s => !latestStatus.TryGetValue(s.Id, out var status) || status == AttendanceStatus.Present);
|
||||
}
|
||||
|
||||
private void LoadPerformance(Guid groupId)
|
||||
{
|
||||
var system = _groupRepository.GetById(groupId)?.GradingSystem ?? GradingSystem.Grades1To6;
|
||||
var gradesByStudent = _grades.GetByGroup(groupId).GroupBy(g => g.StudentId)
|
||||
.ToDictionary(g => g.Key, g => g.Select(x => ParseGradeScore(x.Value, system)).Where(x => x.HasValue)
|
||||
.Select(x => x!.Value).ToList());
|
||||
var entries = _sessions.GetByGroup(groupId).SelectMany(s => _participation.GetBySession(s.Id)).ToList();
|
||||
|
||||
foreach (var student in _participants)
|
||||
{
|
||||
var signals = gradesByStudent.GetValueOrDefault(student.Id, []).ToList();
|
||||
signals.AddRange(entries.Where(e => e.StudentId == student.Id).SelectMany(e => e.Ratings)
|
||||
.Select(r => (Math.Clamp(r.Value, -2, 2) + 2) / 4.0));
|
||||
_performance[student.Id] = signals.Count == 0 ? null : signals.Average();
|
||||
}
|
||||
}
|
||||
|
||||
private List<List<Student>> BuildAssignments(int[] capacities)
|
||||
{
|
||||
var result = capacities.Select(_ => new List<Student>()).ToList();
|
||||
var strength = Math.Abs(PerformanceDistribution) / 100.0;
|
||||
var mean = _performance.Values.Where(x => x.HasValue).Select(x => x!.Value).DefaultIfEmpty(0.5).Average();
|
||||
var ranked = _participants.Select(s => new
|
||||
{
|
||||
Student = s,
|
||||
Score = (_performance.GetValueOrDefault(s.Id) ?? mean) * strength + _random.NextDouble() * (1 - strength),
|
||||
}).OrderByDescending(x => x.Score).ToList();
|
||||
|
||||
if (PerformanceDistribution < -20)
|
||||
{
|
||||
var cursor = 0;
|
||||
for (var i = 0; i < result.Count; i++)
|
||||
for (var j = 0; j < capacities[i]; j++) result[i].Add(ranked[cursor++].Student);
|
||||
}
|
||||
else if (PerformanceDistribution > 20)
|
||||
{
|
||||
var sums = new double[result.Count];
|
||||
foreach (var item in ranked)
|
||||
{
|
||||
var target = Enumerable.Range(0, result.Count).Where(i => result[i].Count < capacities[i])
|
||||
.OrderBy(i => result[i].Count == 0 ? -1 : sums[i] / result[i].Count)
|
||||
.ThenBy(_ => _random.NextDouble()).First();
|
||||
result[target].Add(item.Student);
|
||||
sums[target] += item.Score;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var shuffled = ranked.OrderBy(_ => _random.Next()).Select(x => x.Student).ToList();
|
||||
var cursor = 0;
|
||||
for (var i = 0; i < result.Count; i++)
|
||||
for (var j = 0; j < capacities[i]; j++) result[i].Add(shuffled[cursor++]);
|
||||
}
|
||||
OptimizeAssignments(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
private void OptimizeAssignments(List<List<Student>> groups)
|
||||
{
|
||||
var best = AssignmentPenalty(groups);
|
||||
var improved = true;
|
||||
var passes = 0;
|
||||
while (improved && passes++ < 100)
|
||||
{
|
||||
improved = false;
|
||||
(int AGroup, int AIndex, int BGroup, int BIndex, double Score)? bestSwap = null;
|
||||
for (var firstGroup = 0; firstGroup < groups.Count; firstGroup++)
|
||||
for (var secondGroup = firstGroup + 1; secondGroup < groups.Count; secondGroup++)
|
||||
for (var firstIndex = 0; firstIndex < groups[firstGroup].Count; firstIndex++)
|
||||
for (var secondIndex = 0; secondIndex < groups[secondGroup].Count; secondIndex++)
|
||||
{
|
||||
(groups[firstGroup][firstIndex], groups[secondGroup][secondIndex]) =
|
||||
(groups[secondGroup][secondIndex], groups[firstGroup][firstIndex]);
|
||||
var score = AssignmentPenalty(groups);
|
||||
(groups[firstGroup][firstIndex], groups[secondGroup][secondIndex]) =
|
||||
(groups[secondGroup][secondIndex], groups[firstGroup][firstIndex]);
|
||||
if (score + 0.000001 < best && (bestSwap is null || score < bestSwap.Value.Score))
|
||||
bestSwap = (firstGroup, firstIndex, secondGroup, secondIndex, score);
|
||||
}
|
||||
if (bestSwap is { } swap)
|
||||
{
|
||||
(groups[swap.AGroup][swap.AIndex], groups[swap.BGroup][swap.BIndex]) =
|
||||
(groups[swap.BGroup][swap.BIndex], groups[swap.AGroup][swap.AIndex]);
|
||||
best = swap.Score;
|
||||
improved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private double AssignmentPenalty(List<List<Student>> groups)
|
||||
{
|
||||
var mean = _performance.Values.Where(x => x.HasValue).Select(x => x!.Value).DefaultIfEmpty(0.5).Average();
|
||||
var distributionWeight = Math.Abs(PerformanceDistribution) / 100.0;
|
||||
double performancePenalty;
|
||||
if (PerformanceDistribution < -20)
|
||||
{
|
||||
performancePenalty = groups.Sum(group =>
|
||||
{
|
||||
var values = group.Select(s => _performance.GetValueOrDefault(s.Id) ?? mean).ToList();
|
||||
var groupMean = values.Average();
|
||||
return values.Sum(value => Math.Pow(value - groupMean, 2));
|
||||
});
|
||||
}
|
||||
else if (PerformanceDistribution > 20)
|
||||
{
|
||||
var averages = groups.Select(group => group.Average(s => _performance.GetValueOrDefault(s.Id) ?? mean)).ToList();
|
||||
performancePenalty = averages.Sum(value => Math.Pow(value - averages.Average(), 2));
|
||||
}
|
||||
else performancePenalty = 0;
|
||||
|
||||
var supportPenalty = 0.0;
|
||||
if (DistributeSupportStudents && _supportStudentIds.Count > 0)
|
||||
{
|
||||
var counts = groups.Select(g => g.Count(s => _supportStudentIds.Contains(s.Id))).ToList();
|
||||
supportPenalty = counts.Sum(count => Math.Pow(count - counts.Average(), 2)) * 2.0;
|
||||
}
|
||||
|
||||
var groupByStudent = groups.SelectMany((group, index) => group.Select(s => (s.Id, index)))
|
||||
.ToDictionary(x => x.Id, x => x.index);
|
||||
var forcedPenalty = ForcedPairs.Count(rule => PairViolated(rule, groupByStudent, mustBeTogether: true)) *
|
||||
PairWeight(ForcedPairPriority);
|
||||
var excludedPenalty = ExcludedPairs.Count(rule => PairViolated(rule, groupByStudent, mustBeTogether: false)) *
|
||||
PairWeight(ExcludedPairPriority);
|
||||
return performancePenalty * distributionWeight + supportPenalty + forcedPenalty + excludedPenalty;
|
||||
}
|
||||
|
||||
private int ResolveGroupCount(int participantCount)
|
||||
{
|
||||
var maxGroups = Math.Max(1, participantCount / 2);
|
||||
var requestedCount = Math.Clamp(TargetGroupCount, 1, maxGroups);
|
||||
var sizeBasedCount = Math.Clamp((int)Math.Ceiling(participantCount / (double)Math.Max(2, TargetGroupSize)), 1, maxGroups);
|
||||
if (CountPriority >= 99 && SizePriority < 99) return requestedCount;
|
||||
if (SizePriority >= 99 && CountPriority < 99) return sizeBasedCount;
|
||||
|
||||
return Enumerable.Range(1, maxGroups).MinBy(count =>
|
||||
{
|
||||
var sizeDeviation = Math.Abs(participantCount / (double)count - TargetGroupSize) / Math.Max(2, TargetGroupSize);
|
||||
var countDeviation = Math.Abs(count - requestedCount) / (double)Math.Max(1, requestedCount);
|
||||
return sizeDeviation * (0.05 + SizePriority / 100.0) +
|
||||
countDeviation * (0.05 + CountPriority / 100.0);
|
||||
});
|
||||
}
|
||||
|
||||
private void InvalidateResult()
|
||||
{
|
||||
GeneratedGroups.Clear();
|
||||
HasGeneratedGroups = false;
|
||||
HasUnsavedChanges = false;
|
||||
SaveStatus = "";
|
||||
StatusText = _participants.Count >= 2
|
||||
? $"{_participants.Count} Schüler stehen zur Einteilung bereit."
|
||||
: "Für eine Gruppeneinteilung werden mindestens zwei Schüler benötigt.";
|
||||
UpdateWarning(null);
|
||||
}
|
||||
|
||||
private void UpdateWarning(int? resolvedCount, List<List<Student>>? assignments = null)
|
||||
{
|
||||
var warnings = new List<string>();
|
||||
if (_attendanceWarning.Length > 0) warnings.Add(_attendanceWarning);
|
||||
if (_participants.Count >= 2)
|
||||
{
|
||||
if (_participants.Count != Math.Max(2, TargetGroupSize) * TargetGroupCount)
|
||||
{
|
||||
var resolution = resolvedCount is null ? "" : $" Verwendet werden {resolvedCount} Gruppen.";
|
||||
warnings.Add($"Zielgröße {TargetGroupSize} und {TargetGroupCount} Gruppen sind bei {_participants.Count} Schülern nicht gleichzeitig exakt erfüllbar.{resolution}");
|
||||
}
|
||||
}
|
||||
if (assignments is not null)
|
||||
{
|
||||
var groupByStudent = assignments.SelectMany((group, index) => group.Select(s => (s.Id, index)))
|
||||
.ToDictionary(x => x.Id, x => x.index);
|
||||
var unavailable = ForcedPairs.Concat(ExcludedPairs).Count(rule =>
|
||||
!groupByStudent.ContainsKey(rule.FirstId) || !groupByStudent.ContainsKey(rule.SecondId));
|
||||
var forcedOpen = ForcedPairs.Count(rule => PairViolated(rule, groupByStudent, mustBeTogether: true));
|
||||
var excludedOpen = ExcludedPairs.Count(rule => PairViolated(rule, groupByStudent, mustBeTogether: false));
|
||||
if (unavailable > 0) warnings.Add($"{unavailable} Paarregel(n) sind wegen fehlender Teilnehmender heute nicht anwendbar.");
|
||||
if (forcedOpen > 0) warnings.Add($"{forcedOpen} gewünschte Paarung(en) konnten mit den aktuellen Prioritäten nicht erfüllt werden.");
|
||||
if (excludedOpen > 0) warnings.Add($"{excludedOpen} ausgeschlossene Paarung(en) konnten mit den aktuellen Prioritäten nicht getrennt werden.");
|
||||
}
|
||||
WarningText = string.Join(" ", warnings);
|
||||
}
|
||||
|
||||
private void AddPairRule(ObservableCollection<StudentPairRule> target,
|
||||
ObservableCollection<StudentPairRule> opposite)
|
||||
{
|
||||
PairingMessage = "";
|
||||
if (SelectedPairStudentA is null || SelectedPairStudentB is null)
|
||||
{
|
||||
PairingMessage = "Bitte zwei Schüler auswählen.";
|
||||
return;
|
||||
}
|
||||
if (SelectedPairStudentA.Id == SelectedPairStudentB.Id)
|
||||
{
|
||||
PairingMessage = "Bitte zwei verschiedene Schüler auswählen.";
|
||||
return;
|
||||
}
|
||||
if (target.Any(rule => rule.Matches(SelectedPairStudentA.Id, SelectedPairStudentB.Id)))
|
||||
{
|
||||
PairingMessage = "Diese Paarregel ist bereits vorhanden.";
|
||||
return;
|
||||
}
|
||||
var conflicting = opposite.FirstOrDefault(rule => rule.Matches(SelectedPairStudentA.Id, SelectedPairStudentB.Id));
|
||||
if (conflicting is not null) opposite.Remove(conflicting);
|
||||
StudentPairRule? created = null;
|
||||
created = new StudentPairRule(SelectedPairStudentA, SelectedPairStudentB, rule =>
|
||||
{
|
||||
target.Remove(rule);
|
||||
InvalidateResult();
|
||||
});
|
||||
target.Add(created);
|
||||
SelectedPairStudentA = null;
|
||||
SelectedPairStudentB = null;
|
||||
InvalidateResult();
|
||||
}
|
||||
|
||||
private static bool PairViolated(StudentPairRule rule, IReadOnlyDictionary<Guid, int> groups,
|
||||
bool mustBeTogether)
|
||||
{
|
||||
if (!groups.TryGetValue(rule.FirstId, out var first) || !groups.TryGetValue(rule.SecondId, out var second))
|
||||
return false;
|
||||
return mustBeTogether ? first != second : first == second;
|
||||
}
|
||||
|
||||
private static double PairWeight(double priority) => 0.05 + priority / 100.0 * 8.0;
|
||||
|
||||
private static string PriorityLabel(double value) => value switch
|
||||
{
|
||||
>= 90 => "nahezu fix",
|
||||
>= 65 => "hohe Priorität",
|
||||
>= 35 => "mittlere Priorität",
|
||||
>= 10 => "flexibel",
|
||||
_ => "nur Richtwert",
|
||||
};
|
||||
|
||||
private static double? ParseGradeScore(string value, GradingSystem system)
|
||||
{
|
||||
var text = value.Trim();
|
||||
var tendency = 0.0;
|
||||
if (text.EndsWith('+')) { tendency = system == GradingSystem.Grades1To6 ? -1.0 / 3 : 1.0 / 3; text = text[..^1]; }
|
||||
else if (text.EndsWith('-')) { tendency = system == GradingSystem.Grades1To6 ? 1.0 / 3 : -1.0 / 3; text = text[..^1]; }
|
||||
if (!double.TryParse(text, System.Globalization.NumberStyles.Number,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out var parsed)) return null;
|
||||
parsed += tendency;
|
||||
return system == GradingSystem.Grades1To6
|
||||
? Math.Clamp((6 - parsed) / 5.0, 0, 1)
|
||||
: Math.Clamp(parsed / 15.0, 0, 1);
|
||||
}
|
||||
}
|
||||
@@ -181,8 +181,8 @@ public partial class StudentPerformanceOverviewViewModel : ObservableObject
|
||||
noteEquivalent, warnings.Count > 0, string.Join(" · ", warnings)));
|
||||
if (noteEquivalent.HasValue) previousNoteEquivalent = noteEquivalent;
|
||||
}
|
||||
_examGradesRaw = ExamScoringService.EffectiveGrades(effectiveExamEntries, _gradingSystem)
|
||||
.Select(grade => (Grade: grade, Weight: 1.0)).ToList();
|
||||
var (writtenGrades, testGrades) = ExamScoringService.EffectiveGradesByKind(effectiveExamEntries, _gradingSystem);
|
||||
_examGradesRaw = writtenGrades.Select(grade => (Grade: grade, Weight: 1.0)).ToList();
|
||||
_examsAverage = _examGradesRaw.Count > 0 ? _grading.WeightedAverage(_examGradesRaw) : null;
|
||||
|
||||
// ── Mitarbeit & Sonstige ──────────────────────────────────────────
|
||||
@@ -207,6 +207,9 @@ public partial class StudentPerformanceOverviewViewModel : ObservableObject
|
||||
_otherGradesRaw.Add((g.Value, g.Weight));
|
||||
OtherRows.Add(new StudentSimpleGradeRow(g, SaveGrade));
|
||||
}
|
||||
// Tests u. Ä. aus der Klausurfunktion zählen mit, sind aber hier nicht editierbar
|
||||
// (sie werden in der Punkteeingabe der Arbeit gepflegt).
|
||||
_otherGradesRaw.AddRange(testGrades.Select(grade => (grade, 1.0)));
|
||||
_otherAverage = _otherGradesRaw.Count > 0 ? _grading.WeightedAverage(_otherGradesRaw) : null;
|
||||
|
||||
ExamsAverageDisplay = _examsAverage.HasValue ? FormatGrade(_examsAverage.Value) : null;
|
||||
|
||||
Loaded 100 of 215 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user