feat: add planning JSON exchange

This commit is contained in:
2026-08-17 02:04:29 +02:00
parent 50f3b2d6a9
commit 8efeb68e93
8 changed files with 797 additions and 2 deletions
@@ -1,4 +1,8 @@
using Avalonia.Controls;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Platform;
using Avalonia.Platform.Storage;
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
@@ -11,6 +15,12 @@ namespace LehrerApp.Desktop.Views.Groups;
public partial class PlanningTabView : UserControl
{
private static readonly FilePickerFileType JsonFileType = new("JSON-Dateien")
{
Patterns = ["*.json"],
MimeTypes = ["application/json"],
};
public PlanningTabView() => InitializeComponent();
protected override void OnDataContextChanged(EventArgs e)
@@ -167,4 +177,139 @@ public partial class PlanningTabView : UserControl
await dialog.ShowDialog<bool>(owner);
return dialogVm.Result;
}
private async void OnExportUnit(object? sender, RoutedEventArgs e) => await RunExchange(async () =>
{
if (DataContext is not PlanningTabViewModel { SelectedUnit: { } selected } vm) return;
var topLevel = TopLevel.GetTopLevel(this);
if (topLevel is null) return;
var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = "Unterrichtseinheit exportieren",
SuggestedFileName = $"Einheit_{SafeFileName(selected.Title)}.json",
FileTypeChoices = [JsonFileType],
});
if (file is null) return;
var json = Exchange.ExportUnit(selected.Model, CreateExchangeContext(vm, selected.Title));
await WriteTextAsync(file, json);
Notifications.ShowSuccess("Unterrichtseinheit als JSON exportiert.");
});
private async void OnImportUnit(object? sender, RoutedEventArgs e) => await RunExchange(async () =>
{
if (DataContext is not PlanningTabViewModel { CanImportUnitPlanning: true } vm) return;
var file = await PickJsonFile("Neue Unterrichtseinheit importieren");
if (file is null) return;
var result = Exchange.ImportUnit(await ReadTextAsync(file), vm.GroupId);
vm.RefreshPlanning(result.Unit.Id, result.Lessons.FirstOrDefault()?.Id);
Notifications.ShowSuccess($"Einheit „{result.Unit.Title}“ mit {result.Lessons.Count} Stunde(n) importiert.");
});
private async void OnExportLesson(object? sender, RoutedEventArgs e) => await RunExchange(async () =>
{
if (DataContext is not PlanningTabViewModel { SelectedLesson: { } lesson } vm) return;
var topLevel = TopLevel.GetTopLevel(this);
if (topLevel is null) return;
var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = "Stundenplanung exportieren",
SuggestedFileName = $"Stunde_{lesson.Model.Date:yyyy-MM-dd}_{SafeFileName(lesson.Topic)}.json",
FileTypeChoices = [JsonFileType],
});
if (file is null) return;
var json = Exchange.ExportLesson(lesson.Model,
CreateExchangeContext(vm, vm.SelectedUnit?.Title));
await WriteTextAsync(file, json);
Notifications.ShowSuccess("Stundenplanung als JSON exportiert.");
});
private async void OnImportLesson(object? sender, RoutedEventArgs e) => await RunExchange(async () =>
{
if (DataContext is not PlanningTabViewModel
{ CanImportLessonPlanning: true, SelectedUnit: { } unit } vm) return;
var file = await PickJsonFile("Neue Stundenplanung importieren");
if (file is null) return;
var lesson = Exchange.ImportLesson(await ReadTextAsync(file), unit.Id, vm.GroupId);
vm.RefreshPlanning(unit.Id, lesson.Id);
Notifications.ShowSuccess($"Stunde „{lesson.Topic}“ importiert.");
});
private async void OnCopyUnitFormat(object? sender, RoutedEventArgs e) =>
await CopyFormatDescription("Einheitenplanung-Format.md", "Formatbeschreibung für Einheiten kopiert.");
private async void OnCopyLessonFormat(object? sender, RoutedEventArgs e) =>
await CopyFormatDescription("Stundenplanung-Format.md", "Formatbeschreibung für Stunden kopiert.");
private async Task CopyFormatDescription(string fileName, string successMessage) => await RunExchange(async () =>
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard is null) throw new InvalidOperationException("Die Zwischenablage ist nicht verfügbar.");
var uri = new Uri($"avares://LehrerApp.Desktop/Assets/PlanningFormats/{fileName}");
await using var stream = AssetLoader.Open(uri);
using var reader = new StreamReader(stream);
await clipboard.SetTextAsync(await reader.ReadToEndAsync());
Notifications.ShowSuccess(successMessage);
});
private async Task<IStorageFile?> PickJsonFile(string title)
{
var topLevel = TopLevel.GetTopLevel(this);
if (topLevel is null) return null;
var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
Title = title,
AllowMultiple = false,
FileTypeFilter = [JsonFileType],
});
return files.FirstOrDefault();
}
private static async Task<string> ReadTextAsync(IStorageFile file)
{
await using var stream = await file.OpenReadAsync();
using var reader = new StreamReader(stream);
return await reader.ReadToEndAsync();
}
private static async Task WriteTextAsync(IStorageFile file, string content)
{
await using var stream = await file.OpenWriteAsync();
stream.SetLength(0);
await using var writer = new StreamWriter(stream);
await writer.WriteAsync(content);
}
private static PlanningExchangeContext CreateExchangeContext(PlanningTabViewModel vm, string? unitTitle) => new()
{
Group = vm.GroupLabel,
Subject = vm.SubjectName,
GradeLevel = vm.GradeLevel,
UnitTitle = unitTitle,
};
private static string SafeFileName(string value)
{
var invalid = Path.GetInvalidFileNameChars().ToHashSet();
var safe = new string(value.Select(c => invalid.Contains(c) ? '_' : c).ToArray()).Trim();
return string.IsNullOrWhiteSpace(safe) ? "Planung" : safe;
}
private async Task RunExchange(Func<Task> action)
{
try
{
await action();
}
catch (Exception ex) when (ex is PlanningExchangeException or IOException
or UnauthorizedAccessException or InvalidOperationException)
{
Notifications.ShowError(ex.Message);
}
}
private static PlanningExchangeService Exchange =>
App.Services.GetRequiredService<PlanningExchangeService>();
private static NotificationService Notifications =>
App.Services.GetRequiredService<NotificationService>();
}