Klausur-Deckblätter als Sammel-PDF aus Vorlagen vom Typ exam-cover

Neuer Dialog "Deckblätter…" bei Klausuren, Punktetabelle als Drawing mit
festen Spaltenbreiten, FLOWDRAWBOX-Attribut fit=content, Stapel-Rendering
mit Seitenzahl je Datensatz, Kursbezeichnung und konfigurierbares Kürzel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-07 10:39:09 +02:00
1 parent f56caced32
commit dd92128464
33 files changed
+1158 -28

No files matched your search

+2
View File
@@ -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")));
@@ -211,6 +212,7 @@ public static class AppBootstrapper
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) ──────
@@ -0,0 +1,77 @@
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>
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 = "")
{
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(exam.Title);
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);
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,33 @@
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());
await new ExamCoverSheetDialog { DataContext = vm }.ShowDialog(owner);
}
}
@@ -0,0 +1,82 @@
using System.Globalization;
using LehrerApp.Core.Services;
using LehrerApp.Templating;
namespace LehrerApp.Desktop.Services;
/// <summary>Zeichnet die Punktetabelle des Klausur-Deckblatts (Aufgabe / Max. Punktzahl /
/// Punktzahl). Die Spalten haben eine feste Breite: passen nicht alle Aufgaben nebeneinander in die
/// Box der Vorlage, folgt darunter ein weiterer Tabellenblock, statt alles zu verkleinern. Gedacht
/// für eine <c>FLOWDRAWBOX … fit=content</c>, damit nachfolgende Elemente mitwandern.</summary>
public static class ExamPointsTableDrawingBuilder
{
public const string PlaceholderName = "Exam.PointsTable";
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
// Referenzentwurf in Millimetern, abgemessen an der Schulvorlage.
private const float LabelWidth = 38f, ColumnWidth = 20.5f;
private const float HeaderHeight = 5.5f, MaximumHeight = 8.5f, PointsHeight = 11.5f;
private const float BlockGap = 4f, Padding = 1.5f, Stroke = 0.2f, HeavyStroke = 0.45f;
private const float FontSize = 10f;
/// <param name="contentWidth">Breite der deklarierten Box in der Maßeinheit der Vorlage.</param>
/// <param name="millimeterScale">1 mm in der Maßeinheit der Vorlage (siehe
/// <see cref="LetterPlaceholderBuilder.FindDeclaredDrawingBox(LoadedTemplate, string)"/>).</param>
public static DrawingValue Build(IReadOnlyList<ExamCoverTaskColumn> columns, float contentWidth = 170,
float millimeterScale = 1)
{
if (columns.Count == 0) return new DrawingValue([], 0);
var k = millimeterScale;
var perBlock = ColumnsPerBlock(contentWidth, millimeterScale);
// Halbe Strichstärke Abstand zum Rand, sonst schneidet die Box die äußeren Linien an.
var origin = HeavyStroke / 2 * k;
var blockHeight = (HeaderHeight + MaximumHeight + PointsHeight) * k;
var commands = new List<DrawingCommand>();
var y = origin;
for (var start = 0; start < columns.Count; start += perBlock)
{
if (start > 0) y += BlockGap * k;
var block = columns.Skip(start).Take(perBlock).ToList();
var maximumY = y + HeaderHeight * k;
var pointsY = maximumY + MaximumHeight * k;
Cell(commands, origin, y, LabelWidth * k, HeaderHeight * k, "Aufgabe", DrawingTextAlignment.AlignRight, false, k);
Cell(commands, origin, maximumY, LabelWidth * k, MaximumHeight * k, "Max. Punktzahl", DrawingTextAlignment.AlignRight, false, k);
Cell(commands, origin, pointsY, LabelWidth * k, PointsHeight * k, "Punktzahl", DrawingTextAlignment.AlignRight, true, k);
for (var index = 0; index < block.Count; index++)
{
var column = block[index];
var x = origin + (LabelWidth + index * ColumnWidth) * k;
Cell(commands, x, y, ColumnWidth * k, HeaderHeight * k,
column.IsBonus ? "" : $"Nr. {column.Number}", DrawingTextAlignment.AlignCenter, false, k);
Cell(commands, x, maximumY, ColumnWidth * k, MaximumHeight * k,
(column.IsBonus ? "+" : "") + Format(column.MaxPoints), DrawingTextAlignment.AlignCenter, false, k);
Cell(commands, x, pointsY, ColumnWidth * k, PointsHeight * k,
column.AchievedPoints is { } achieved ? Format(achieved) : "", DrawingTextAlignment.AlignCenter, false, k);
}
commands.Add(new DrawLine(origin, pointsY, origin + (LabelWidth + block.Count * ColumnWidth) * k, pointsY,
StrokeWidth: HeavyStroke * k));
y += blockHeight;
}
return new DrawingValue(commands, y + origin);
}
/// <summary>Wie viele Aufgaben bei fester Spaltenbreite nebeneinander in die Box passen.</summary>
public static int ColumnsPerBlock(float contentWidth, float millimeterScale = 1) =>
Math.Max(1, (int)Math.Floor((contentWidth / millimeterScale - HeavyStroke - LabelWidth + 0.01f) / ColumnWidth));
private static void Cell(List<DrawingCommand> commands, float x, float y, float width, float height,
string text, DrawingTextAlignment alignment, bool bold, float k)
{
commands.Add(new DrawRectangle(x, y, width, height, StrokeWidth: Stroke * k));
if (text.Length == 0) return;
// DrawStringEx setzt die Grundlinie auf Y + Schriftgröße; so sitzt die Zeile optisch mittig.
var fontHeight = FontSize * UnitConverter.Points(1, "pt") / UnitConverter.Points(1, "mm") * k;
var textY = y + height / 2 - fontHeight * 0.64f;
commands.Add(new DrawStringEx(x + Padding * k, textY, y + height - textY, width - 2 * Padding * k, text,
alignment, FontSize, Bold: bold));
}
private static string Format(double value) => value.ToString("0.##", German);
}
@@ -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))
{
try
{
@@ -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 */ }
}
}
@@ -43,6 +43,7 @@ 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;
@@ -177,6 +178,13 @@ public partial class ExamsOverviewViewModel : ObservableObject
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,116 @@
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;
[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;
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 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 = "")
{
_teacherAbbreviation = teacherAbbreviation;
_exam = exam; _group = group; _subjectName = subjectName; _grading = grading; _renderer = renderer;
_loader = templateStores[0];
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.</summary>
public bool Generate(string outputPath)
{
StatusMessage = "";
if (SelectedTemplate is null) 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);
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))).ToList();
var result = _renderer.RenderBatchToPdf(loaded, data);
File.WriteAllBytes(outputPath, result.Pdf);
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)
{ StatusMessage = $"Deckblätter konnten nicht erzeugt werden: {ex.Message}"; return false; }
}
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 };
}
}
@@ -54,25 +54,14 @@ public partial class ExamGradingDialogViewModel : ObservableObject
var membershipList = memberships.GetByGroup(groupId);
var existing = results.GetByExam(exam.Id).ToDictionary(r => r.StudentId);
// Nachschreibarbeit: nur Schüler, die die erste Arbeit nicht mitgeschrieben haben. Wer dort
// schon eine Note hat, taucht nicht auf — außer es gibt hier bereits ein Ergebnis (nichts
// verstecken, was schon eingetragen wurde).
var wroteOriginal = new HashSet<Guid>();
if (exam.IsMakeUp && exam.RepeatOfExamId is { } originalId)
foreach (var r in results.GetByExam(originalId).Where(r => !r.Absent && r.Grade is not null))
wroteOriginal.Add(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 (result is null && wroteOriginal.Contains(s.Id)) continue;
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;
@@ -235,6 +235,7 @@ public partial class GroupDetailViewModel : 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>? OnExamCoverSheets { get; set; }
public Func<Task<bool>>? OnConfirmReactivate { get; set; }
public GroupDetailViewModel(IGroupRepository groups, IStudentRepository students,
@@ -421,6 +422,15 @@ public partial class GroupDetailViewModel : ObservableObject
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()
{
@@ -496,6 +506,7 @@ public partial class GroupDetailViewModel : ObservableObject
GradeExamCommand.NotifyCanExecuteChanged();
EvaluateExamCommand.NotifyCanExecuteChanged();
RevealExamCommand.NotifyCanExecuteChanged();
ExamCoverSheetsCommand.NotifyCanExecuteChanged();
DuplicateExamCommand.NotifyCanExecuteChanged();
DeleteExamCommand.NotifyCanExecuteChanged();
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
@@ -526,6 +537,7 @@ public partial class GroupDetailViewModel : ObservableObject
GradeExamCommand.NotifyCanExecuteChanged();
EvaluateExamCommand.NotifyCanExecuteChanged();
RevealExamCommand.NotifyCanExecuteChanged();
ExamCoverSheetsCommand.NotifyCanExecuteChanged();
DuplicateExamCommand.NotifyCanExecuteChanged();
DeleteExamCommand.NotifyCanExecuteChanged();
AdvanceExamStatusCommand.NotifyCanExecuteChanged();
@@ -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)) Templates.Add(new(template));
SelectedTemplate = Templates.FirstOrDefault();
foreach (var id in studentIds)
if (students.GetById(id) is { } student) Students.Add(new(student));
@@ -1,5 +1,6 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LehrerApp.Desktop.Services;
using LehrerApp.Templating;
using System.Collections.ObjectModel;
@@ -7,6 +8,13 @@ namespace LehrerApp.Desktop.ViewModels.Settings;
public partial class SettingsViewModel
{
private readonly TeacherSettingsService? _teacherSettings;
/// <summary>Eigenes Kürzel für Formulare (Platzhalter <c>Teacher.Abbreviation</c> auf dem
/// Klausur-Deckblatt). Wird sofort gespeichert; im Deckblatt-Dialog je Druck überschreibbar.</summary>
[ObservableProperty] private string _teacherAbbreviation = "";
partial void OnTeacherAbbreviationChanged(string value) => _teacherSettings?.SaveAbbreviation(value);
[ObservableProperty] private string _worksheetTemplateStatus = "";
public ObservableCollection<LetterTemplateListItem> WorksheetTemplateList { get; } = [];
@@ -121,8 +121,11 @@ public partial class SettingsViewModel : ObservableObject
AppearanceSettingsService appearance, TrashViewModel trashTab,
SnapshotService? snapshotService = null, SyncEngine? syncEngine = null,
UntisSyncService? untisSync = null, AnnualPlanSyncService? annualPlanSync = null,
SchoolWeatherService? schoolWeather = null, WebUntisIntegrationService? untisIntegration = null)
SchoolWeatherService? schoolWeather = null, WebUntisIntegrationService? untisIntegration = null,
TeacherSettingsService? teacherSettings = null)
{
_teacherSettings = teacherSettings;
_teacherAbbreviation = teacherSettings?.LoadAbbreviation() ?? "";
_logger = logger;
_syncKeyRecovery = syncKeyRecovery;
SyncKeyWasRegenerated = syncKeyStatus.KeyWasRegenerated;
@@ -60,7 +60,7 @@ public partial class CreateLetterDialogViewModel : ObservableObject
_attendanceCalendarFactory = attendanceCalendarFactory;
_absenceDayListFactory = absenceDayListFactory;
_attendanceDataRefresher = attendanceDataRefresher;
foreach (var template in templates.GetTemplates()) Templates.Add(new(template));
foreach (var template in templates.GetTemplates().Where(x => !x.IsExamCover)) Templates.Add(new(template));
foreach (var contact in student.Contacts.Where(c => !c.InvalidSince.HasValue).OrderBy(c => c.Name)) Contacts.Add(new(contact));
foreach (var membership in memberships.GetByStudent(student.Id))
if (groups.GetById(membership.GroupId) is { } group) Groups.Add(new(group));
@@ -177,6 +177,8 @@
<Button Content="Einzelansicht" Command="{Binding RevealSelectedCommand}"
IsVisible="{Binding ShowGradeSummary}"
ToolTip.Tip="Zeigt das Ergebnis eines einzelnen Schülers – zunächst nur den Namen, erst nach „Aufdecken“ Note und Punkte."/>
<Button Content="Deckblätter…" Command="{Binding CoverSheetsSelectedCommand}"
ToolTip.Tip="Individuelle Deckblätter für diese Arbeit als ein PDF erzeugen."/>
<Button Content="Zum Kurs →" Command="{Binding GoToGroupCommand}" HorizontalAlignment="Right"/>
</StackPanel>
</StackPanel>
@@ -2,6 +2,7 @@ using Avalonia.Controls;
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.Services;
using LehrerApp.Desktop.ViewModels;
using LehrerApp.Desktop.ViewModels.Exams;
using LehrerApp.Desktop.ViewModels.Groups;
@@ -24,6 +25,7 @@ public partial class ExamsOverviewView : UserControl
vm.OnGradeExam = ShowGradeExamDialog;
vm.OnEvaluateExam = ShowEvaluateExamDialog;
vm.OnRevealExam = ShowRevealExamDialog;
vm.OnCoverSheets = exam => ExamCoverSheetDialogs.ShowAsync(this, exam);
vm.OnNavigateToGroup = groupId => App.Services.GetRequiredService<MainWindowViewModel>()
.NavigateToGroupDetail(groupId, GroupDetailKlausurenTabIndex);
}
@@ -0,0 +1,59 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:LehrerApp.Desktop.ViewModels.Groups"
x:Class="LehrerApp.Desktop.Views.Groups.ExamCoverSheetDialog"
x:DataType="vm:ExamCoverSheetDialogViewModel"
Title="Deckblätter drucken"
Width="460" Height="640"
CanResize="False" WindowStartupLocation="CenterOwner">
<Grid RowDefinitions="Auto,Auto,*,Auto,Auto" Margin="24">
<StackPanel Grid.Row="0" Spacing="4" Margin="0,0,0,14">
<TextBlock Text="Deckblätter drucken" Classes="dialogtitle"/>
<TextBlock Text="{Binding ExamLabel}" FontSize="12" Opacity="0.65" TextWrapping="Wrap"/>
</StackPanel>
<StackPanel Grid.Row="1" Spacing="10" Margin="0,0,0,14">
<TextBlock Text="Vorlage" FontSize="12" FontWeight="SemiBold" Opacity="0.7"/>
<ComboBox ItemsSource="{Binding Templates}" SelectedItem="{Binding SelectedTemplate}"
HorizontalAlignment="Stretch" DisplayMemberBinding="{Binding Name}"/>
<TextBlock Text="Noch keine Deckblatt-Vorlage importiert — in den Einstellungen unter „Briefvorlagen“ eine .lavorlage-Datei mit dem Metadatum report-type=exam-cover hinzufügen."
Classes="emptyhint" TextWrapping="Wrap"
IsVisible="{Binding HasNoTemplates}"/>
<Grid ColumnDefinitions="Auto,*" ColumnSpacing="12">
<TextBlock Grid.Column="0" Text="Kürzel" VerticalAlignment="Center"/>
<TextBox Grid.Column="1" Text="{Binding TeacherAbbreviation}" PlaceholderText="z. B. MON HED"
ToolTip.Tip="Vorbelegt mit dem eigenen Kürzel aus den Einstellungen. Änderungen gelten nur für diesen Druck."/>
</Grid>
<CheckBox Content="Punkte und Note eintragen" IsChecked="{Binding FillResults}"
ToolTip.Tip="Aus: Blanko-Deckblatt mit Namen und leerer Punktetabelle zum Ausfüllen von Hand."/>
</StackPanel>
<ScrollViewer Grid.Row="2">
<StackPanel Spacing="4">
<TextBlock Text="Für diese Schüler erzeugen" FontSize="12" FontWeight="SemiBold" Opacity="0.7" Margin="0,0,0,4"/>
<ItemsControl ItemsSource="{Binding Students}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="vm:ExamCoverStudentChoice">
<Grid ColumnDefinitions="*,Auto" Margin="0,3">
<CheckBox Grid.Column="0" Content="{Binding FullName}" IsChecked="{Binding IsIncluded}"/>
<TextBlock Grid.Column="1" Text="{Binding Hint}" FontSize="11" Opacity="0.6" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</ScrollViewer>
<TextBlock Grid.Row="3" Text="{Binding StatusMessage}" FontSize="12" Margin="0,10,0,0" TextWrapping="Wrap"
IsVisible="{Binding StatusMessage, Converter={x:Static StringConverters.IsNotNullOrEmpty}}"/>
<Grid Grid.Row="4" ColumnDefinitions="*,8,*" Margin="0,16,0,0">
<Button Grid.Column="0" Content="Schließen" HorizontalAlignment="Stretch" Click="OnClose"/>
<Button Grid.Column="2" Content="PDF erzeugen…" HorizontalAlignment="Stretch" Click="OnGenerate"
IsEnabled="{Binding !HasNoTemplates}"/>
</Grid>
</Grid>
</Window>
@@ -0,0 +1,29 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using LehrerApp.Desktop.ViewModels.Groups;
namespace LehrerApp.Desktop.Views.Groups;
public partial class ExamCoverSheetDialog : Window
{
public ExamCoverSheetDialog() => InitializeComponent();
private async void OnGenerate(object? sender, RoutedEventArgs e)
{
if (DataContext is not ExamCoverSheetDialogViewModel vm) return;
var file = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = "Deckblätter speichern",
SuggestedFileName = vm.SuggestedFileName,
DefaultExtension = "pdf",
FileTypeChoices = [new FilePickerFileType("PDF") { Patterns = ["*.pdf"] }],
});
if (file is null) return;
var path = file.Path.LocalPath;
if (vm.Generate(path))
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(path) { UseShellExecute = true });
}
private void OnClose(object? sender, RoutedEventArgs e) => Close();
}
@@ -120,6 +120,8 @@
<Button Content="Auswertung" Command="{Binding EvaluateExamCommand}"/>
<Button Content="Einzelansicht" Command="{Binding RevealExamCommand}"
ToolTip.Tip="Zeigt das Ergebnis eines einzelnen Schülers – zunächst nur den Namen, erst nach „Aufdecken“ Note und Punkte."/>
<Button Content="Deckblätter…" Command="{Binding ExamCoverSheetsCommand}"
ToolTip.Tip="Individuelle Deckblätter für diese Arbeit als ein PDF erzeugen."/>
<Button Content="Bearbeiten" Command="{Binding EditExamCommand}"/>
<Button Content="Duplizieren" Command="{Binding DuplicateExamCommand}"/>
<SplitButton Content="Status ▸" Command="{Binding AdvanceExamStatusCommand}">
@@ -167,6 +169,7 @@
<MenuItem Header="Punkte eingeben" Command="{Binding GradeExamCommand}"/>
<MenuItem Header="Auswertung" Command="{Binding EvaluateExamCommand}"/>
<MenuItem Header="Einzelansicht" Command="{Binding RevealExamCommand}"/>
<MenuItem Header="Deckblätter…" Command="{Binding ExamCoverSheetsCommand}"/>
<MenuItem Header="Bearbeiten" Command="{Binding EditExamCommand}"/>
<MenuItem Header="Duplizieren" Command="{Binding DuplicateExamCommand}"/>
<MenuItem Header="Status">
@@ -38,6 +38,7 @@ public partial class GroupDetailView : UserControl
vm.OnGradeExam = ShowGradeExamDialog;
vm.OnEvaluateExam = ShowEvaluateExamDialog;
vm.OnRevealExam = ShowRevealExamDialog;
vm.OnExamCoverSheets = exam => ExamCoverSheetDialogs.ShowAsync(this, exam);
vm.OnConfirmReactivate = ShowReactivateConfirmDialog;
vm.OverviewTab.OnNavigateToWorkload = () =>
App.Services.GetRequiredService<MainWindowViewModel>().NavigateToWorkload();
@@ -515,6 +515,15 @@
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Separator Margin="0,8"/>
<TextBlock Text="Klausur-Deckblätter" FontSize="15" FontWeight="SemiBold"/>
<TextBlock Text="Vorlagen mit dem Metadatum report-type=exam-cover erscheinen nur unter „Deckblätter…“ bei einer Klausur, egal in welche der beiden Listen oben sie importiert wurden. Das Kürzel füllt den Platzhalter Teacher.Abbreviation und lässt sich beim Erzeugen noch ändern, etwa für einen gemeinsam unterrichteten Kurs."
FontSize="12" Opacity="0.65" TextWrapping="Wrap"/>
<StackPanel Orientation="Horizontal" Spacing="12">
<TextBlock Text="Eigenes Kürzel" VerticalAlignment="Center"/>
<TextBox Text="{Binding TeacherAbbreviation}" Width="120" PlaceholderText="z. B. HED"/>
</StackPanel>
</StackPanel>
</ScrollViewer>
</ContentPage>