WIP (unstable): WebUntis-iCal-Abgleich für Vertretungen/Ausfälle
Erkennt Vertretungen, Ausfälle und Zusatzaufsichten aus dem persönlichen WebUntis-iCal-Feed und schreibt sie automatisch als SubstitutionEntry. Bekannter offener Bug: es tauchen weiterhin falsche Vertretungen für Stunden auf, die real unverändert sind — wird in einem Folge-Commit untersucht, deshalb vorerst auf diesem Branch statt main. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -124,9 +124,25 @@ public interface ISubstitutionEntryRepository
|
||||
{
|
||||
List<SubstitutionEntry> GetAll();
|
||||
List<SubstitutionEntry> GetByDate(DateOnly date);
|
||||
/// Für den WebUntis-Abgleich (idempotentes Update statt Duplikat je iCal-UID).
|
||||
SubstitutionEntry? GetByExternalId(string externalId);
|
||||
void Save(SubstitutionEntry entry);
|
||||
void Delete(Guid id);
|
||||
}
|
||||
/// Zuletzt bekannter Zustand aller WebUntis-iCal-Termine, für den Abgleich bei jedem Abruf.
|
||||
public interface IUntisSnapshotRepository
|
||||
{
|
||||
List<UntisSnapshotEntry> GetAll();
|
||||
void Save(UntisSnapshotEntry entry);
|
||||
void Delete(Guid id);
|
||||
}
|
||||
/// Vom Nutzer bestätigte Zuordnungen WebUntis-Wochenmuster → LearningGroup.
|
||||
public interface IUntisSlotMappingRepository
|
||||
{
|
||||
List<UntisSlotMapping> GetAll();
|
||||
void Save(UntisSlotMapping mapping);
|
||||
void Delete(Guid id);
|
||||
}
|
||||
public interface IDocumentationRepository
|
||||
{
|
||||
List<Documentation> GetByStudent(Guid studentId);
|
||||
|
||||
@@ -210,6 +210,12 @@ public class SubstitutionEntry
|
||||
/// Bezeichnung (bei SpecialAssignment, z.B. "Ausflug ins Museum", "Berufsmesse").
|
||||
public string Description { get; set; } = "";
|
||||
public string? Notes { get; set; }
|
||||
/// Gesetzt, wenn dieser Eintrag automatisch aus dem WebUntis-iCal-Abgleich entstanden ist —
|
||||
/// trägt die stabile iCal-UID des auslösenden Termins. Macht wiederholte Abgleich-Läufe
|
||||
/// idempotent (Update statt Duplikat, siehe ISubstitutionEntryRepository.GetByExternalId) und
|
||||
/// unterscheidet automatisch erzeugte von von Hand eingetragenen Ausnahmen. Bei Handeinträgen
|
||||
/// (SubstitutionEntryDialogViewModel) bleibt es null.
|
||||
public string? ExternalId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
namespace LehrerApp.Core.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Zuletzt bekannter Zustand eines einzelnen WebUntis-iCal-Termins (ein VEVENT) — die lokale
|
||||
/// "Sicherungskopie", gegen die jeder neue Abruf verglichen wird, um Änderungen zu erkennen
|
||||
/// (Nutzer-Feedback: "Abgleich mit einem lokalen Backup, um Änderungen zu finden"). <see cref="Uid"/>
|
||||
/// ist die stabile iCal-UID des Termins (pro Wochen-Slot über das ganze Schuljahr gleich) und
|
||||
/// dient als fachlicher Schlüssel für den Abgleich — bewusst kein <c>[BsonId]</c> darauf, da
|
||||
/// LehrerApp.Core absichtlich frei von LiteDB/Avalonia-Abhängigkeiten bleibt (siehe CLAUDE.md);
|
||||
/// die Suche nach <see cref="Uid"/> läuft stattdessen über eine gefilterte Repository-Abfrage.
|
||||
/// </summary>
|
||||
public class UntisSnapshotEntry
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
public string Uid { get; set; } = "";
|
||||
public DateOnly Date { get; set; }
|
||||
public TimeOnly StartTime { get; set; }
|
||||
public TimeOnly EndTime { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public string Location { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
public string Status { get; set; } = "CONFIRMED";
|
||||
public DateTime LastSeenAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Vom Nutzer bestätigte Zuordnung eines regulären WebUntis-Wochenmusters (Wochentag + Uhrzeit +
|
||||
/// Fach-Kürzel + Klassen-Token aus der Beschreibung) zu einer bestehenden <see cref="LearningGroup"/>
|
||||
/// (<see cref="SubstitutionKind.Lesson"/>) oder — für Termine ohne Klassenbezug, z.B. Aufsichten —
|
||||
/// zu einer festen Pause (<see cref="SubstitutionKind.Supervision"/>, <see cref="AfterPeriod"/>
|
||||
/// statt <see cref="GroupId"/>/<see cref="PeriodNumber"/>; Nutzer-Feedback: "Zwei Termine sind
|
||||
/// meine Aufsichten, die nicht zugeordnet werden können [...] vom Zeitraster und von der Dauer her
|
||||
/// könnten die erfasst werden" — Aufsichten liegen in Pausen, nicht auf einem Unterrichtsstunden-
|
||||
/// Zeitraster, brauchen also einen eigenen Auflösungsweg statt PeriodNumber). Nur bestätigte
|
||||
/// (<see cref="Confirmed"/> true) Zuordnungen lösen automatisch geschriebene
|
||||
/// <see cref="SubstitutionEntry"/>-Einträge aus (Nutzer-Feedback: die erstmalige Zuordnung ist
|
||||
/// fehleranfällig — falsche Gruppe würde falsche Vertretungen erzeugen — und braucht deshalb eine
|
||||
/// Bestätigung, bevor sie aktiv wird; siehe UntisMappingReviewDialog).
|
||||
/// </summary>
|
||||
public class UntisSlotMapping
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
public DayOfWeek Weekday { get; set; }
|
||||
public TimeOnly StartTime { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public string ClassToken { get; set; } = "";
|
||||
public SubstitutionKind Kind { get; set; } = SubstitutionKind.Lesson;
|
||||
/// Nur bei <see cref="SubstitutionKind.Lesson"/> gesetzt.
|
||||
public Guid? GroupId { get; set; }
|
||||
/// Erste/primäre Stunde, zum Bestätigungszeitpunkt über PeriodScheduleService aufgelöst (siehe
|
||||
/// UntisMatchingService) — hier gespeichert, damit UntisDiffService selbst framework-frei
|
||||
/// bleibt und keine eigene Uhrzeit→Stunde-Auflösung braucht. Nur bei
|
||||
/// <see cref="SubstitutionKind.Lesson"/> gesetzt.
|
||||
public int? PeriodNumber { get; set; }
|
||||
/// ALLE Stunden, die dieser WebUntis-Termin überdeckt (siehe UntisSlotMatch.CoveredPeriods) —
|
||||
/// bei einer Doppelstunde mehr als eine. Entscheidet, welche TimetableSlots als "durch WebUntis
|
||||
/// bestätigt" gelten (Nutzer-Feedback: "ich habe aber jetzt alles zugeordnet, und trotzdem
|
||||
/// erhalte ich die Warnung, dass 16 Stunden ohne Untis-Zuordnung sind" — ohne diese Liste blieb
|
||||
/// die zweite Stunde einer Doppelstunde immer "unzugeordnet", weil WebUntis dafür nur einen
|
||||
/// einzigen, am Anfang beginnenden Termin meldet). Nur bei <see cref="SubstitutionKind.Lesson"/>
|
||||
/// gesetzt.
|
||||
public List<int> CoveredPeriods { get; set; } = [];
|
||||
/// Nur bei <see cref="SubstitutionKind.Supervision"/> gesetzt — wie bei
|
||||
/// <see cref="SupervisionDuty.AfterPeriod"/>, ebenfalls zum Bestätigungszeitpunkt aufgelöst
|
||||
/// (die Pause direkt vor der WebUntis-Startzeit, 0 = vor der 1. Stunde).
|
||||
public int? AfterPeriod { get; set; }
|
||||
public bool Confirmed { get; set; }
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace LehrerApp.Core.Services;
|
||||
|
||||
/// <summary>Ein einzelner Termin (VEVENT) aus einer geparsten iCal-Datei — z.B. aus dem
|
||||
/// WebUntis-Stundenplan-Export (TODO.md, "WebUntis-iCal-Abgleich").</summary>
|
||||
public class UntisIcsEvent
|
||||
{
|
||||
public string Uid { get; set; } = "";
|
||||
public DateOnly Date { get; set; }
|
||||
public DayOfWeek Weekday => Date.DayOfWeek;
|
||||
public TimeOnly StartTime { get; set; }
|
||||
public TimeOnly EndTime { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public string Location { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
public string Status { get; set; } = "CONFIRMED";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bewusst kein vollständiger RFC-5545-Parser, sondern genau der Ausschnitt, den der reale
|
||||
/// WebUntis-Export tatsächlich nutzt (verifiziert an einem echten Export, siehe Planungsdokument):
|
||||
/// flache VEVENT-Liste ohne RRULE-Wiederholung, ohne Line-Folding, ohne VALARM. `DTSTART;TZID=...`
|
||||
/// wird als lokale Wanduhrzeit gelesen (die App kennt ohnehin nur "lokale Zeit" der Schule, siehe
|
||||
/// PeriodScheduleService) — ein `...Z`-Suffix (UTC) wird defensiv unterstützt, auch wenn im realen
|
||||
/// Export nicht beobachtet. Termine mit unbekanntem DTSTART-Format werden übersprungen statt die
|
||||
/// gesamte Verarbeitung abzubrechen (gleiche Fail-soft-Haltung wie EventApplier in LehrerApp.Sync).
|
||||
/// </summary>
|
||||
public static class IcsParser
|
||||
{
|
||||
private static readonly TimeZoneInfo BerlinTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
|
||||
|
||||
public static List<UntisIcsEvent> Parse(string icsText)
|
||||
{
|
||||
var lines = Unfold(icsText);
|
||||
var events = new List<UntisIcsEvent>();
|
||||
Dictionary<string, (string Params, string Value)>? current = null;
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (line == "BEGIN:VEVENT") { current = []; continue; }
|
||||
if (line == "END:VEVENT")
|
||||
{
|
||||
if (current is not null && TryBuildEvent(current, out var evt)) events.Add(evt);
|
||||
current = null;
|
||||
continue;
|
||||
}
|
||||
if (current is null) continue;
|
||||
|
||||
var (key, paramsPart, value) = SplitPropertyLine(line);
|
||||
if (key.Length == 0) continue;
|
||||
current[key] = (paramsPart, value);
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
// RFC 5545 Line-Folding: eine Fortsetzungszeile beginnt mit Leerzeichen/Tab und gehört zur
|
||||
// Vorzeile — im realen WebUntis-Export nicht beobachtet (Zeilen deutlich unter dem 75-Oktett-
|
||||
// Limit), aber defensiv unterstützt, falls sich der Export einmal ändert.
|
||||
private static List<string> Unfold(string icsText)
|
||||
{
|
||||
var rawLines = icsText.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||
var result = new List<string>();
|
||||
foreach (var raw in rawLines)
|
||||
{
|
||||
if ((raw.StartsWith(' ') || raw.StartsWith('\t')) && result.Count > 0)
|
||||
result[^1] += raw[1..];
|
||||
else
|
||||
result.Add(raw);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// "KEY;PARAM=VAL;PARAM2=VAL2:VALUE" — der erste unescapte Doppelpunkt trennt Wert vom Rest.
|
||||
private static (string Key, string Params, string Value) SplitPropertyLine(string line)
|
||||
{
|
||||
var colonIndex = line.IndexOf(':');
|
||||
if (colonIndex < 0) return ("", "", "");
|
||||
var head = line[..colonIndex];
|
||||
var value = line[(colonIndex + 1)..];
|
||||
var semiIndex = head.IndexOf(';');
|
||||
return semiIndex < 0 ? (head, "", value) : (head[..semiIndex], head[(semiIndex + 1)..], value);
|
||||
}
|
||||
|
||||
private static bool TryBuildEvent(Dictionary<string, (string Params, string Value)> props, out UntisIcsEvent evt)
|
||||
{
|
||||
evt = new UntisIcsEvent();
|
||||
if (!props.TryGetValue("UID", out var uid) || string.IsNullOrWhiteSpace(uid.Value)) return false;
|
||||
evt.Uid = uid.Value;
|
||||
|
||||
if (!props.TryGetValue("DTSTART", out var dtStart) || !TryParseLocalDateTime(dtStart, out var start))
|
||||
return false;
|
||||
evt.Date = DateOnly.FromDateTime(start);
|
||||
evt.StartTime = TimeOnly.FromDateTime(start);
|
||||
|
||||
if (props.TryGetValue("DTEND", out var dtEnd) && TryParseLocalDateTime(dtEnd, out var end))
|
||||
evt.EndTime = TimeOnly.FromDateTime(end);
|
||||
|
||||
evt.Summary = props.TryGetValue("SUMMARY", out var summary) && !string.IsNullOrWhiteSpace(summary.Value)
|
||||
? Unescape(summary.Value) : null;
|
||||
evt.Location = props.TryGetValue("LOCATION", out var location) ? Unescape(location.Value) : "";
|
||||
evt.Description = props.TryGetValue("DESCRIPTION", out var description) ? Unescape(description.Value) : "";
|
||||
evt.Status = props.TryGetValue("STATUS", out var status) && !string.IsNullOrWhiteSpace(status.Value)
|
||||
? status.Value : "CONFIRMED";
|
||||
return true;
|
||||
}
|
||||
|
||||
// "TZID=Europe/Berlin:20260817T075000" (lokale Wanduhrzeit) oder "20260817T075000Z" (UTC).
|
||||
private static bool TryParseLocalDateTime((string Params, string Value) prop, out DateTime local)
|
||||
{
|
||||
local = default;
|
||||
var value = prop.Value;
|
||||
var isUtc = value.EndsWith('Z');
|
||||
var digits = isUtc ? value[..^1] : value;
|
||||
|
||||
if (!DateTime.TryParseExact(digits, "yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.None, out var parsed))
|
||||
return false;
|
||||
|
||||
local = isUtc
|
||||
? TimeZoneInfo.ConvertTimeFromUtc(DateTime.SpecifyKind(parsed, DateTimeKind.Utc), BerlinTimeZone)
|
||||
: parsed;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string Unescape(string value)
|
||||
{
|
||||
var sb = new StringBuilder(value.Length);
|
||||
for (var i = 0; i < value.Length; i++)
|
||||
{
|
||||
if (value[i] == '\\' && i + 1 < value.Length)
|
||||
{
|
||||
var next = value[i + 1];
|
||||
sb.Append(next switch { ';' => ';', ',' => ',', 'n' or 'N' => '\n', '\\' => '\\', _ => next });
|
||||
i++;
|
||||
}
|
||||
else sb.Append(value[i]);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Core.Services;
|
||||
|
||||
public sealed class UntisDiffResult
|
||||
{
|
||||
/// SubstitutionEntry-Kandidaten (Id ist immer neu vergeben — der Aufrufer entscheidet über
|
||||
/// ISubstitutionEntryRepository.GetByExternalId, ob ein vorhandener Eintrag aktualisiert
|
||||
/// statt dupliziert werden muss; siehe UntisSyncService).
|
||||
public List<SubstitutionEntry> SubstitutionsToSave { get; init; } = [];
|
||||
public List<UntisSnapshotEntry> SnapshotToSave { get; init; } = [];
|
||||
/// Verschwundene, bereits als Ausfall verarbeitete Zeilen — werden aus dem Snapshot entfernt,
|
||||
/// damit derselbe Ausfall nicht bei jedem weiteren Poll erneut erkannt wird.
|
||||
public List<Guid> SnapshotIdsToDelete { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stufe 2 des WebUntis-Abgleichs: ein neuer iCal-Abruf gegen den zuletzt gespeicherten
|
||||
/// Schnappschuss (Nutzer-Feedback: "Abgleich mit einem lokalen Backup, um Änderungen zu finden").
|
||||
/// Framework-frei wie <see cref="UntisMatchingService"/> — nimmt nur einfache Objekte/Listen
|
||||
/// entgegen, kein Datenbankzugriff.
|
||||
/// </summary>
|
||||
public class UntisDiffService
|
||||
{
|
||||
public const int DefaultLookaheadDays = 14;
|
||||
|
||||
public UntisDiffResult Diff(List<UntisIcsEvent> newEvents, List<UntisSnapshotEntry> previousSnapshot,
|
||||
List<UntisSlotMapping> confirmedMappings, DateOnly today, int lookaheadDays = DefaultLookaheadDays,
|
||||
List<SupervisionDuty>? existingSupervisionDuties = null, HashSet<DateOnly>? freeDates = null)
|
||||
{
|
||||
var previousByUid = previousSnapshot.ToDictionary(s => s.Uid);
|
||||
// GroupBy statt direktem ToDictionary: robust gegen mehrere Mappings für denselben Slot
|
||||
// (z.B. Altdaten vor einem Bugfix) - die zuletzt angelegte gewinnt, statt mit einer
|
||||
// ArgumentException abzubrechen und dadurch den gesamten Poll (Timer-Callback) zu killen.
|
||||
var mappingByWeekdayStart = confirmedMappings
|
||||
.Where(m => m.Confirmed && (m.Kind == SubstitutionKind.Lesson ? m.PeriodNumber is not null : m.AfterPeriod is not null))
|
||||
.GroupBy(m => (m.Weekday, m.StartTime))
|
||||
.ToDictionary(g => g.Key, g => g.OrderByDescending(m => m.CreatedAt).First());
|
||||
// Regelmäßige, ohnehin schon jede Woche im Stundenplan sichtbare Aufsichten (siehe
|
||||
// SupervisionDuty/Einstellungen "Aufsichten") - eine bestätigte Supervision-Zuordnung, die
|
||||
// KEINER davon entspricht, ist per Definition eine zusätzliche/Vertretungsaufsicht und soll
|
||||
// deshalb selbst als reguläres Vorkommnis (nicht erst bei Abweichung) im Plan auftauchen.
|
||||
var regularDutyKeys = (existingSupervisionDuties ?? [])
|
||||
.Select(d => (d.Weekday, d.AfterPeriod))
|
||||
.ToHashSet();
|
||||
|
||||
var substitutions = new List<SubstitutionEntry>();
|
||||
var snapshotToSave = new List<UntisSnapshotEntry>();
|
||||
var newEventsByUid = newEvents.ToDictionary(e => e.Uid);
|
||||
|
||||
foreach (var evt in newEvents)
|
||||
{
|
||||
snapshotToSave.Add(new UntisSnapshotEntry
|
||||
{
|
||||
Id = previousByUid.TryGetValue(evt.Uid, out var existing) ? existing.Id : Guid.NewGuid(),
|
||||
Uid = evt.Uid, Date = evt.Date, StartTime = evt.StartTime, EndTime = evt.EndTime,
|
||||
Summary = evt.Summary, Location = evt.Location, Description = evt.Description,
|
||||
Status = evt.Status, LastSeenAt = DateTime.UtcNow,
|
||||
});
|
||||
|
||||
if (!mappingByWeekdayStart.TryGetValue((evt.Weekday, evt.StartTime), out var mapping)) continue;
|
||||
|
||||
if (string.Equals(evt.Status, "CANCELLED", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
substitutions.Add(mapping.Kind == SubstitutionKind.Lesson
|
||||
? BuildCancelledLesson(evt.Date, mapping, evt.Uid)
|
||||
: BuildSupervisionNote(evt.Date, mapping, evt.Uid, "Laut WebUntis abgesagt."));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (mapping.Kind == SubstitutionKind.Lesson)
|
||||
{
|
||||
if (HasDeviated(evt, mapping))
|
||||
substitutions.Add(BuildChangedLesson(evt, mapping));
|
||||
}
|
||||
else if (!regularDutyKeys.Contains((mapping.Weekday, mapping.AfterPeriod!.Value)))
|
||||
{
|
||||
// Nutzer-Feedback: "Auch die Extra-Aufsicht ist dann nicht im Plan [...] So macht
|
||||
// doch der Sync nur so halb Sinn" - ohne passende reguläre Aufsicht IST dieses
|
||||
// Vorkommnis selbst schon die meldenswerte Vertretung, nicht erst eine Abweichung
|
||||
// davon.
|
||||
substitutions.Add(BuildSupervisionNote(evt.Date, mapping, evt.Uid, "Zusätzliche Aufsicht laut WebUntis."));
|
||||
}
|
||||
}
|
||||
|
||||
// Aufsichten: weiterhin rein reaktiv gegen den letzten Snapshot (kein fester wöchentlicher
|
||||
// Anspruch, siehe "Zusätzliche Aufsicht" oben - ein Verschwinden ist nur meldenswert, wenn
|
||||
// die Aufsicht vorher tatsächlich einmal gesehen wurde).
|
||||
var snapshotIdsToDelete = new List<Guid>();
|
||||
foreach (var previous in previousSnapshot)
|
||||
{
|
||||
if (newEventsByUid.ContainsKey(previous.Uid)) continue;
|
||||
if (previous.Date < today || previous.Date > today.AddDays(lookaheadDays)) continue;
|
||||
if (!mappingByWeekdayStart.TryGetValue((previous.Date.DayOfWeek, previous.StartTime), out var mapping)) continue;
|
||||
if (mapping.Kind != SubstitutionKind.Supervision) continue;
|
||||
|
||||
var vanishedId = BuildVanishedExternalId(previous.Date, mapping);
|
||||
substitutions.Add(BuildSupervisionNote(previous.Date, mapping, vanishedId, "Laut WebUntis entfallen oder übernommen."));
|
||||
snapshotIdsToDelete.Add(previous.Id);
|
||||
}
|
||||
|
||||
// Unterrichtsstunden: zusätzlich AKTIV prüfen, ob für jedes vom Feed bereits abgedeckte
|
||||
// künftige Datum dieses Wochentags ein passender Termin existiert - rein reaktives
|
||||
// Schnappschuss-Diffing (oben) erkennt nur Termine, die zwischen zwei Abrufen
|
||||
// VERSCHWINDEN, nicht solche, die schon beim allerersten Abruf nie im Feed auftauchten
|
||||
// (Nutzer-Feedback: "Am 27.08. fällt eine Stunde NAT in der 8c aus. Dieser Ausfall steht
|
||||
// nicht im Plan [...] die Klasse ist dort weg, der Unterricht wird definitiv nicht
|
||||
// stattfinden" - WebUntis hatte diesen Ausfall von Anfang an nie als Termin gelistet, es
|
||||
// gab also nie einen Schnappschuss-Eintrag, der hätte "verschwinden" können). Begrenzt auf
|
||||
// das vom Feed tatsächlich abgedeckte Zeitfenster (jüngstes gesehenes Datum), damit nicht
|
||||
// Tage jenseits des vom Feed veröffentlichten Horizonts fälschlich als Ausfall gelten, und
|
||||
// um Ferien/Feiertage bereinigt (freeDates), an denen WebUntis ohnehin keinen Termin führt.
|
||||
if (newEvents.Count > 0)
|
||||
{
|
||||
var maxKnownDate = newEvents.Max(e => e.Date);
|
||||
var horizonEnd = maxKnownDate < today.AddDays(lookaheadDays) ? maxKnownDate : today.AddDays(lookaheadDays);
|
||||
var eventDates = newEvents.Select(e => (e.Date, e.StartTime)).ToHashSet();
|
||||
var freeDateSet = freeDates ?? [];
|
||||
|
||||
foreach (var mapping in mappingByWeekdayStart.Values.Where(m => m.Kind == SubstitutionKind.Lesson))
|
||||
{
|
||||
for (var date = today; date <= horizonEnd; date = date.AddDays(1))
|
||||
{
|
||||
if (date.DayOfWeek != mapping.Weekday) continue;
|
||||
if (freeDateSet.Contains(date)) continue;
|
||||
if (eventDates.Contains((date, mapping.StartTime))) continue;
|
||||
|
||||
substitutions.Add(BuildCancelledLesson(date, mapping, BuildMissingExternalId(date, mapping)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new UntisDiffResult
|
||||
{
|
||||
SubstitutionsToSave = substitutions, SnapshotToSave = snapshotToSave,
|
||||
SnapshotIdsToDelete = snapshotIdsToDelete,
|
||||
};
|
||||
}
|
||||
|
||||
// Nutzer-Feedback: "Ich habe das aufgelöst und den Mathematik E-Kurs ausgewählt [...] Diese
|
||||
// manuelle Verknüpfung ist aber jetzt scheinbar vergessen" — Ursache: ClassToken wird beim
|
||||
// Bestätigen kompakt ohne Leerzeichen gespeichert ("10a;10b;10c"), WebUntis trennt die
|
||||
// Klassen in DESCRIPTION aber mit "; " (Semikolon + Leerzeichen), z.B. "10a; 10b; 10c;
|
||||
// Gastro HED" — ein reiner Teilstring-Vergleich schlug für JEDE kombinierte/differenzierte
|
||||
// Gruppe (mehr als ein Klassen-Token) strukturell fehl, unabhängig von der tatsächlich
|
||||
// gewählten Gruppe. Fix: beide Seiten vor dem Vergleich von Leerzeichen befreien (gleiches
|
||||
// Prinzip wie UntisMatchingService.Normalize für den Gruppennamen-Abgleich).
|
||||
private static bool HasDeviated(UntisIcsEvent evt, UntisSlotMapping mapping) =>
|
||||
evt.Summary != mapping.Summary || !RemoveWhitespace(evt.Description).Contains(mapping.ClassToken);
|
||||
|
||||
private static string RemoveWhitespace(string value) =>
|
||||
new(value.Where(c => !char.IsWhiteSpace(c)).ToArray());
|
||||
|
||||
private static SubstitutionEntry BuildCancelledLesson(DateOnly date, UntisSlotMapping mapping, string externalId) => new()
|
||||
{
|
||||
Date = date, Kind = SubstitutionKind.Cancelled, PeriodNumber = mapping.PeriodNumber,
|
||||
Description = "Automatisch über WebUntis-Abgleich erkannt.", ExternalId = externalId,
|
||||
};
|
||||
|
||||
private static SubstitutionEntry BuildChangedLesson(UntisIcsEvent evt, UntisSlotMapping mapping) => new()
|
||||
{
|
||||
Date = evt.Date, Kind = SubstitutionKind.Lesson, PeriodNumber = mapping.PeriodNumber,
|
||||
GroupId = mapping.GroupId, GroupLabel = mapping.ClassToken,
|
||||
Description = $"WebUntis: {evt.Summary ?? "?"} · {evt.Location} (regulär: {mapping.Summary ?? "?"})",
|
||||
ExternalId = evt.Uid,
|
||||
};
|
||||
|
||||
// Aufsichten haben keinen TimetableSlot im Hintergrund (siehe SubstitutionEntry.Kind-Doc) -
|
||||
// deshalb Kind=Supervision statt Cancelled, auch wenn der Termin verschwunden ist.
|
||||
private static SubstitutionEntry BuildSupervisionNote(DateOnly date, UntisSlotMapping mapping,
|
||||
string externalId, string reason) => new()
|
||||
{
|
||||
Date = date, Kind = SubstitutionKind.Supervision, AfterPeriod = mapping.AfterPeriod,
|
||||
Description = $"Automatisch über WebUntis-Abgleich erkannt: {reason}", ExternalId = externalId,
|
||||
};
|
||||
|
||||
// Ein verschwundener Termin hat keine eigene UID mehr im neuen Fetch - ein aus Slot+Datum
|
||||
// abgeleiteter Ersatzschlüssel dient weiter als Idempotenz-Schlüssel für spätere Polls.
|
||||
private static string BuildVanishedExternalId(DateOnly date, UntisSlotMapping mapping) =>
|
||||
$"vanished-{mapping.Id}-{date:yyyyMMdd}";
|
||||
|
||||
// Für eine von Anfang an fehlende Stunde gibt es nie eine echte iCal-UID - ein aus
|
||||
// Slot+Datum abgeleiteter Schlüssel macht wiederholte Polls trotzdem idempotent (Update
|
||||
// statt Duplikat), unabhängig vom Snapshot-Stand.
|
||||
private static string BuildMissingExternalId(DateOnly date, UntisSlotMapping mapping) =>
|
||||
$"missing-{mapping.Id}-{date:yyyyMMdd}";
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Core.Services;
|
||||
|
||||
/// <summary>Ein aus vielen Wochen-Vorkommen abgeleitetes reguläres WebUntis-Wochenmuster
|
||||
/// (Nutzer-Feedback: "eine fuzzy logic, die erst mal die regulären Fächer meiner ical meinem
|
||||
/// Stundenplan in der App zuordnet").</summary>
|
||||
public sealed class UntisWeeklyPattern
|
||||
{
|
||||
public DayOfWeek Weekday { get; init; }
|
||||
public TimeOnly StartTime { get; init; }
|
||||
public TimeOnly EndTime { get; init; }
|
||||
public string? Summary { get; init; }
|
||||
/// Klassen-Token(s) aus DESCRIPTION, Lehrkraft-Kürzel bereits abgetrennt — bei kombinierten
|
||||
/// Gruppen mehrere Einträge (z.B. ["10a", "10b", "10c", "Gastro"]).
|
||||
public List<string> ClassTokens { get; init; } = [];
|
||||
public int OccurrenceCount { get; init; }
|
||||
}
|
||||
|
||||
public sealed class UntisSlotMatch
|
||||
{
|
||||
public required UntisWeeklyPattern Pattern { get; init; }
|
||||
/// Erste/primäre Stunde, gesetzt wenn das Muster einen Klassenbezug hat (Unterrichtsstunde) —
|
||||
/// entspricht CoveredPeriods[0].
|
||||
public int? PeriodNumber { get; init; }
|
||||
/// ALLE Stunden, die dieser WebUntis-Termin überdeckt — bei einer Doppelstunde meldet WebUntis
|
||||
/// EINEN Termin über beide Stundenzeiten hinweg (z.B. 07:50–09:20 für Stunde 1+2), während der
|
||||
/// Stundenplan der App dafür ZWEI TimetableSlot-Einträge (Stunde 1 UND Stunde 2) haben kann.
|
||||
/// Ohne diese Liste würde die zweite Stunde nie als "zugeordnet" gelten, selbst nachdem der
|
||||
/// Nutzer das Muster bestätigt hat (Nutzer-Feedback: "ich habe aber jetzt alles zugeordnet,
|
||||
/// und trotzdem erhalte ich die Warnung, dass 16 Stunden ohne Untis-Zuordnung sind").
|
||||
public List<int> CoveredPeriods { get; init; } = [];
|
||||
/// Gesetzt, wenn das Muster KEINEN Klassenbezug hat (z.B. Aufsicht/Springstunde) — die Pause
|
||||
/// direkt vor der Startzeit (0 = vor der 1. Stunde), siehe UntisSlotMapping.AfterPeriod.
|
||||
public int? AfterPeriod { get; init; }
|
||||
public bool IsSupervisionCandidate => Pattern.ClassTokens.Count == 0;
|
||||
public Guid? SuggestedGroupId { get; init; }
|
||||
public bool IsConfident { get; init; }
|
||||
}
|
||||
|
||||
public sealed class UntisMatchResult
|
||||
{
|
||||
public List<UntisSlotMatch> Matches { get; init; } = [];
|
||||
/// Vorhandene TimetableSlots, zu denen sich kein passendes WebUntis-Wochenmuster finden ließ
|
||||
/// (Nutzer-Feedback: "oder der Stundenplan gar nicht mehr passt").
|
||||
public List<TimetableSlot> UnmatchedTimetableSlots { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stufe 1 des WebUntis-Abgleichs (siehe TODO.md): aus einem vollen iCal-Abruf (typischerweise
|
||||
/// ein Schuljahr an Einzelterminen, siehe IcsParser) das reguläre Wochenmuster ableiten und gegen
|
||||
/// den in der App gepflegten Stundenplan (TimetableSlot/LearningGroup) abgleichen. Framework-frei
|
||||
/// wie AttendanceBalanceService — reine Objekte rein, reine Objekte raus, ohne Datenbank- oder
|
||||
/// HTTP-Zugriff, dadurch ohne Mocking testbar.
|
||||
/// </summary>
|
||||
public class UntisMatchingService
|
||||
{
|
||||
// Kleine Toleranz gegen Minuten-Rundungsdifferenzen zwischen dem konfigurierten Stundenraster
|
||||
// und den tatsächlichen WebUntis-Zeiten.
|
||||
private const int StartTimeToleranceMinutes = 3;
|
||||
|
||||
public UntisMatchResult BuildMatches(List<UntisIcsEvent> events, List<LearningGroup> groups,
|
||||
List<TimetableSlot> timetableSlots, PeriodScheduleService periodSchedule)
|
||||
{
|
||||
var teacherToken = DetectTeacherToken(events);
|
||||
var patterns = BuildWeeklyPatterns(events, teacherToken);
|
||||
|
||||
var matches = new List<UntisSlotMatch>();
|
||||
foreach (var pattern in patterns)
|
||||
{
|
||||
// Kein Klassenbezug (z.B. Aufsicht/Springstunde, Nutzer-Feedback: "Zwei Termine sind
|
||||
// meine Aufsichten, die nicht zugeordnet werden können") - liegt typischerweise in
|
||||
// einer Pause, nicht auf einer Unterrichtsstunden-Startzeit, deshalb eigener,
|
||||
// grundsätzlich immer auflösbarer Weg statt ResolvePeriodNumber.
|
||||
if (pattern.ClassTokens.Count == 0)
|
||||
{
|
||||
matches.Add(new UntisSlotMatch { Pattern = pattern, AfterPeriod = ResolveAfterPeriod(pattern.StartTime, periodSchedule) });
|
||||
continue;
|
||||
}
|
||||
|
||||
var coveredPeriods = ResolveCoveredPeriods(pattern.StartTime, pattern.EndTime, periodSchedule);
|
||||
var periodNumber = coveredPeriods.Count > 0 ? coveredPeriods[0] : ResolvePeriodNumber(pattern.StartTime, periodSchedule);
|
||||
var (groupId, confident) = ResolveGroup(pattern.ClassTokens, periodNumber, groups, timetableSlots);
|
||||
matches.Add(new UntisSlotMatch
|
||||
{
|
||||
Pattern = pattern, PeriodNumber = periodNumber, CoveredPeriods = coveredPeriods,
|
||||
SuggestedGroupId = groupId, IsConfident = confident,
|
||||
});
|
||||
}
|
||||
|
||||
var matchedSlotKeys = matches
|
||||
.Where(m => m.SuggestedGroupId is not null)
|
||||
.SelectMany(m => (m.CoveredPeriods.Count > 0 ? m.CoveredPeriods : m.PeriodNumber is { } p ? [p] : [])
|
||||
.Select(period => (m.Pattern.Weekday, period, m.SuggestedGroupId!.Value)))
|
||||
.ToHashSet();
|
||||
var unmatchedSlots = timetableSlots
|
||||
.Where(s => !matchedSlotKeys.Contains((s.Weekday, s.PeriodNumber, s.GroupId)))
|
||||
.ToList();
|
||||
|
||||
return new UntisMatchResult { Matches = matches, UnmatchedTimetableSlots = unmatchedSlots };
|
||||
}
|
||||
|
||||
/// Häufigstes letztes Wort in DESCRIPTION über alle Termine — bei einem persönlichen Feed
|
||||
/// konstant das eigene Kürzel, bewusst nicht hartkodiert (siehe Planungsdokument).
|
||||
private static string? DetectTeacherToken(List<UntisIcsEvent> events) =>
|
||||
events
|
||||
.Select(e => LastToken(e.Description))
|
||||
.Where(t => t is not null)
|
||||
.GroupBy(t => t)
|
||||
.OrderByDescending(g => g.Count())
|
||||
.Select(g => g.Key)
|
||||
.FirstOrDefault();
|
||||
|
||||
private static string? LastToken(string description)
|
||||
{
|
||||
var parts = description.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
return parts.Length == 0 ? null : parts[^1];
|
||||
}
|
||||
|
||||
private static List<UntisWeeklyPattern> BuildWeeklyPatterns(List<UntisIcsEvent> events, string? teacherToken)
|
||||
{
|
||||
var withTokens = events.Select(e => new
|
||||
{
|
||||
Event = e,
|
||||
ClassTokens = ExtractClassTokens(e.Description, teacherToken),
|
||||
});
|
||||
|
||||
var patterns = new List<UntisWeeklyPattern>();
|
||||
foreach (var group in withTokens.GroupBy(x => (x.Event.Weekday, x.Event.StartTime, x.Event.EndTime)))
|
||||
{
|
||||
var modal = group
|
||||
.GroupBy(x => (x.Event.Summary, ClassTokens: string.Join(";", x.ClassTokens)))
|
||||
.OrderByDescending(g => g.Count())
|
||||
.First();
|
||||
|
||||
patterns.Add(new UntisWeeklyPattern
|
||||
{
|
||||
Weekday = group.Key.Weekday,
|
||||
StartTime = group.Key.StartTime,
|
||||
EndTime = group.Key.EndTime,
|
||||
Summary = modal.Key.Summary,
|
||||
ClassTokens = modal.Key.ClassTokens.Length == 0
|
||||
? [] : modal.Key.ClassTokens.Split(';').ToList(),
|
||||
OccurrenceCount = modal.Count(),
|
||||
});
|
||||
}
|
||||
return patterns;
|
||||
}
|
||||
|
||||
// "10a; 10b; 10c; Gastro HED" -> ["10a", "10b", "10c", "Gastro"] (Lehrkraft-Token entfernt).
|
||||
private static List<string> ExtractClassTokens(string description, string? teacherToken)
|
||||
{
|
||||
var withoutTeacher = teacherToken is not null && description.EndsWith(teacherToken)
|
||||
? description[..^teacherToken.Length].TrimEnd()
|
||||
: description;
|
||||
if (string.IsNullOrWhiteSpace(withoutTeacher)) return [];
|
||||
return withoutTeacher.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
|
||||
}
|
||||
|
||||
private static int? ResolvePeriodNumber(TimeOnly startTime, PeriodScheduleService periodSchedule)
|
||||
{
|
||||
var exact = periodSchedule.Periods.FirstOrDefault(p => p.Start == startTime);
|
||||
if (exact is not null) return exact.PeriodNumber;
|
||||
|
||||
var closest = periodSchedule.Periods
|
||||
.Select(p => (Period: p, DiffMinutes: Math.Abs((p.Start.ToTimeSpan() - startTime.ToTimeSpan()).TotalMinutes)))
|
||||
.Where(t => t.DiffMinutes <= StartTimeToleranceMinutes)
|
||||
.OrderBy(t => t.DiffMinutes)
|
||||
.FirstOrDefault();
|
||||
return closest.Period?.PeriodNumber;
|
||||
}
|
||||
|
||||
// Alle konfigurierten Stunden, die vollständig innerhalb [start, end) liegen — bei einer
|
||||
// einzelnen Stunde genau eine, bei einer von WebUntis zu einem Termin zusammengefassten
|
||||
// Doppelstunde entsprechend zwei (siehe UntisSlotMatch.CoveredPeriods).
|
||||
private static List<int> ResolveCoveredPeriods(TimeOnly start, TimeOnly end, PeriodScheduleService periodSchedule)
|
||||
{
|
||||
var tolerance = TimeSpan.FromMinutes(StartTimeToleranceMinutes);
|
||||
return periodSchedule.Periods
|
||||
.Where(p => p.Start.ToTimeSpan() >= start.ToTimeSpan() - tolerance
|
||||
&& p.End.ToTimeSpan() <= end.ToTimeSpan() + tolerance)
|
||||
.OrderBy(p => p.PeriodNumber)
|
||||
.Select(p => p.PeriodNumber)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
// Die Pause direkt vor startTime: die zuletzt endende konfigurierte Stunde davor, 0 (vor der
|
||||
// 1. Stunde) falls keine liegt - anders als ResolvePeriodNumber immer auflösbar, da eine
|
||||
// Pause per Definition zwischen/vor Stunden liegt statt exakt auf einer Startzeit.
|
||||
private static int ResolveAfterPeriod(TimeOnly startTime, PeriodScheduleService periodSchedule) =>
|
||||
periodSchedule.Periods
|
||||
.Where(p => p.End <= startTime)
|
||||
.OrderByDescending(p => p.End)
|
||||
.Select(p => (int?)p.PeriodNumber)
|
||||
.FirstOrDefault() ?? 0;
|
||||
|
||||
private static (Guid? GroupId, bool Confident) ResolveGroup(List<string> classTokens, int? periodNumber,
|
||||
List<LearningGroup> groups, List<TimetableSlot> timetableSlots)
|
||||
{
|
||||
if (classTokens.Count == 0) return (null, false);
|
||||
|
||||
var candidates = classTokens
|
||||
.Select(token => ResolveSingleGroup(token, groups))
|
||||
.Where(g => g is not null)
|
||||
.Select(g => g!)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
|
||||
if (candidates.Count == 1) return (candidates[0].Id, true);
|
||||
if (candidates.Count == 0) return (null, false);
|
||||
|
||||
// Mehrere Klassen im selben Termin (kombinierte/differenzierte Gruppen) — die Gruppe
|
||||
// bevorzugen, die an dieser Stelle bereits einen TimetableSlot hat.
|
||||
if (periodNumber is { } period)
|
||||
{
|
||||
var withExistingSlot = candidates
|
||||
.Where(g => timetableSlots.Any(s => s.GroupId == g.Id && s.PeriodNumber == period))
|
||||
.ToList();
|
||||
if (withExistingSlot.Count == 1) return (withExistingSlot[0].Id, true);
|
||||
}
|
||||
return (null, false); // mehrdeutig - der Nutzer entscheidet im Review-Dialog
|
||||
}
|
||||
|
||||
private static LearningGroup? ResolveSingleGroup(string token, List<LearningGroup> groups)
|
||||
{
|
||||
var exact = groups.FirstOrDefault(g => string.Equals(g.Name, token, StringComparison.OrdinalIgnoreCase));
|
||||
if (exact is not null) return exact;
|
||||
|
||||
var normalizedToken = Normalize(token);
|
||||
return groups.FirstOrDefault(g => Normalize(g.Name) == normalizedToken);
|
||||
}
|
||||
|
||||
private static string Normalize(string value) =>
|
||||
new(value.Where(c => !char.IsWhiteSpace(c)).Select(char.ToLowerInvariant).ToArray());
|
||||
}
|
||||
Reference in New Issue
Block a user