UI verbessert, 2. PDF als kompakte Variante
This commit is contained in:
1 parent
1bf3283029
commit
f9e3e94629
23 files changed
+1009
-146
No files matched your search
+29
-7
@@ -93,7 +93,7 @@ Alle Tabellen liegen in `~/Library/Application Support/LektorenPlan/lektorenplan
|
||||
| `absences` | Abwesenheitszeiträume je Person inkl. Grund |
|
||||
| `service_templates` | Wiederkehrende Gottesdienste (Wochentag, Uhrzeit, benötigte Dienste, Gültigkeit) |
|
||||
| `service_exceptions` | Ausgesetzte Termine einer Vorlage (z. B. wegen Fest oder Ferien) |
|
||||
| `services` | Konkrete Termine, erzeugt aus Vorlagen oder als Sondergottesdienst |
|
||||
| `services` | Konkrete Termine, erzeugt aus Vorlagen oder als Sondergottesdienst; optionaler Freitext-Ort |
|
||||
| `assignments` | Einsatz einer Person in einer Rolle, optional gesperrt |
|
||||
| `liturgical_days` | Liturgischer Tag, Rang, Farbe, Lesungen, Quelle |
|
||||
| `settings` | Zeitraum, Filter, Kalender- und Planungseinstellungen |
|
||||
@@ -239,15 +239,32 @@ vorhandenen Daten.
|
||||
|
||||
## 10. PDF und Druck
|
||||
|
||||
- A4 quer, eigener Renderer mit AppKit/CoreGraphics.
|
||||
**Übersichtlicher Plan (A4 quer)**
|
||||
|
||||
- Eigener Renderer mit AppKit/CoreGraphics.
|
||||
- Kopfbereich mit Zeitraum, Erstellungsdatum und Quellenhinweis; wiederholte
|
||||
Kirchenspalten auf jeder Seite.
|
||||
- Ein Tagesblock mit Datum, Liturgie, Lesungen und den Diensten aller vier
|
||||
Kirchen. Hochfeste und Sonntage sind farblich hinterlegt.
|
||||
- Automatischer Seitenumbruch mit wiederholtem Kopf und Fuß
|
||||
(„Seite n“).
|
||||
Kirchen. Hochfeste und Sonntage sind farblich hinterlegt. Sondergottesdienste
|
||||
zeigen zusätzlich ihren freien Ort.
|
||||
- Automatischer Seitenumbruch mit wiederholtem Kopf und Fuß („Seite n“).
|
||||
|
||||
**Kompakte Gottesdienstliste (A4 hoch)**
|
||||
|
||||
- Nur Tage mit Gottesdiensten, eine Zeile pro Gottesdienst.
|
||||
- Spalten: verkürztes Datum (nur einmal pro Tag, links), Gottesdienst mit
|
||||
Kirche bzw. freiem Ort und Uhrzeit, Lektoren und Kommunionhelfer mit
|
||||
Nachnamen.
|
||||
- Offene Plätze werden als „offen“ ausgewiesen; Hochfeste und
|
||||
Sondergottesdienste erhalten einen kurzen Hinweis.
|
||||
- Sonntage und Hochfeste sind zart hinterlegt; Kopf, Fuß und Seitenzahlen
|
||||
wiederholen sich auf jeder Seite.
|
||||
|
||||
**Gemeinsam**
|
||||
|
||||
- Vorschau über PDFKit mit Aktionen „Sichern“ und „Drucken“.
|
||||
- Druck über `NSPrintInfo` in Querformat, ohne zusätzliche Ränder.
|
||||
- Druck über `NSPrintInfo`; die Ausrichtung folgt dem Seitenformat
|
||||
(quer bzw. hoch), ohne zusätzliche Ränder.
|
||||
|
||||
---
|
||||
|
||||
@@ -262,7 +279,12 @@ vorhandenen Daten.
|
||||
- Planer mit harten Regeln, Scoring, Fairness und Begründungen für Lücken.
|
||||
- Kalender, Zeitstrahl, Filter, Suche, Detaildialog und manuelle Planung.
|
||||
- Gottesdienstordnung, Teamverwaltung, Statistik, Austausch und Einstellungen.
|
||||
- PDF-Vorschau, Druck und App-Bundle.
|
||||
- Sondergottesdienste mit Kirche/Zuordnung und optionalem Freitext-Ort
|
||||
(Open-Air, Sonderorte).
|
||||
- PDF-Vorschau in zwei Varianten, Druck und App-Bundle.
|
||||
- Datenverwaltung: Demo-Daten zurücksetzen oder alle Inhalte löschen; nach dem
|
||||
Löschen wird der Demo-Bestand beim nächsten Start nicht automatisch
|
||||
wiederhergestellt.
|
||||
|
||||
**Bewusste Grenzen**
|
||||
|
||||
|
||||
@@ -6,6 +6,21 @@ Kommunionhelferinnen/-helfern in der Pfarreiengemeinschaft Bad Godesberg
|
||||
|
||||
Das ausführliche Grobkonzept liegt in [CONCEPT.md](CONCEPT.md).
|
||||
|
||||
## Webversion
|
||||
|
||||
Unter [`web/`](web/) liegt eine funktional entsprechende Browserfassung in Go
|
||||
mit SQLite, Mehrbenutzerbetrieb und Mandantentrennung. Sie ist CGO-frei und
|
||||
lässt sich für Linux/arm64 bauen; die macOS-App bleibt unverändert.
|
||||
|
||||
```bash
|
||||
cd web
|
||||
go run . -seed-demo -demo
|
||||
# → http://localhost:8080, Demo-Zugänge: admin/admin123, editor/editor123, reader/reader123
|
||||
```
|
||||
|
||||
Details zu Betrieb, Rollen, Deployment und Sicherheit stehen in
|
||||
[web/README.md](web/README.md).
|
||||
|
||||
## Voraussetzungen
|
||||
|
||||
- macOS 14 oder neuer
|
||||
@@ -30,7 +45,9 @@ starten.
|
||||
Die App legt ihre Datenbank unter
|
||||
`~/Library/Application Support/LektorenPlan/lektorenplan.sqlite` an und befüllt
|
||||
sie beim ersten Start mit Demo-Daten. Über **Einstellungen → Demo-Daten
|
||||
zurücksetzen** lässt sich der Ausgangszustand wiederherstellen.
|
||||
zurücksetzen** lässt sich der Ausgangszustand wiederherstellen; **Alle Daten
|
||||
löschen** entfernt den kompletten Bestand und verhindert, dass die Demo-Daten
|
||||
beim nächsten Start automatisch wieder angelegt werden.
|
||||
|
||||
## Funktionsüberblick
|
||||
|
||||
@@ -44,14 +61,17 @@ zurücksetzen** lässt sich der Ausgangszustand wiederherstellen.
|
||||
- **Manuelle Nachsteuerung:** Kandidatenvorschläge mit Warnhinweisen,
|
||||
Einsätze sperren oder entfernen.
|
||||
- **Gottesdienstordnung:** wiederkehrende Vorlagen, Ausnahmen und
|
||||
Sondergottesdienste.
|
||||
Sondergottesdienste. Sondergottesdienste können statt einer Kirche einen
|
||||
freien Ort (z. B. Open-Air) tragen.
|
||||
- **Team:** Personen, Rollen, Präferenzen, Abwesenheiten, Monatslimits.
|
||||
- **Statistik:** Besetzungsquote, Fairness, Monatsverlauf, Kirchenverteilung,
|
||||
Präferenztreffer, Einsatzübersicht (Swift Charts).
|
||||
- **Austausch:** JSON-Export und -Import für Planungsabschnitte oder Ressourcen
|
||||
mit Vorschau vor dem Zusammenführen.
|
||||
- **PDF & Druck:** A4 quer mit automatischer Pagination, PDFKit-Vorschau,
|
||||
Sichern und direkter Druck.
|
||||
- **PDF & Druck:** zwei Varianten – A4 quer mit Kirchenspalten, Lesungen und
|
||||
automatischer Pagination sowie eine kompakte A4-hoch-Liste mit einer Zeile
|
||||
pro Gottesdienst (Kirche/Ort, Uhrzeit, Nachnamen von Lektoren und
|
||||
Kommunionhelfern). Beide mit PDFKit-Vorschau, Sichern und direkter Druck.
|
||||
|
||||
## Liturgische Daten
|
||||
|
||||
@@ -100,15 +120,21 @@ LP_SNAPSHOT=/tmp/plan.png "$BIN/LektorenPlan"
|
||||
LP_SNAPSHOT=/tmp/statistik.png LP_SNAPSHOT_VIEW=statistics \
|
||||
LP_SNAPSHOT_HEIGHT=2000 "$BIN/LektorenPlan"
|
||||
LP_PDF=/tmp/plan.pdf "$BIN/LektorenPlan"
|
||||
LP_PDF=/tmp/liste.pdf LP_PDF_VARIANT=compact "$BIN/LektorenPlan"
|
||||
```
|
||||
|
||||
`LP_PDF_VARIANT=compact` erzeugt die reduzierte A4-hoch-Liste. Mit
|
||||
`LP_RESET_DEMO=/tmp/report.txt` (optional `LP_RESET_MODE=delete` oder `none`)
|
||||
lässt sich der Datenbank-Neuaufbau automatisiert prüfen; die App schreibt
|
||||
anschließend die Datensatzanzahl in die Report-Datei.
|
||||
|
||||
`LP_SNAPSHOT_VIEW` akzeptiert `planning`, `root`, `team`, `order`,
|
||||
`statistics`, `exchange` und `settings`. Der Auto-Sync ist bei
|
||||
Snapshot-Läufen deaktiviert.
|
||||
|
||||
## Status
|
||||
|
||||
Prototyp 0.1. Die Demo-Personen und Kontaktdaten sind fiktiv. Produktive
|
||||
Version 0.9. Die Demo-Personen und Kontaktdaten sind fiktiv. Produktive
|
||||
Aspekte wie Benutzerkonten, Benachrichtigungen, Signierung und ein
|
||||
Mehrbenutzerbetrieb sind noch nicht umgesetzt; siehe Abschnitt „Grenzen“ in
|
||||
[CONCEPT.md](CONCEPT.md).
|
||||
+11
-2
@@ -52,9 +52,11 @@ cat > "$CONTENTS/Info.plist" <<'PLIST'
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1</string>
|
||||
<string>0.9</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>BuildDate</key>
|
||||
<string>__BUILD_ISO_DATE__</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>14.0</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
@@ -62,9 +64,16 @@ cat > "$CONTENTS/Info.plist" <<'PLIST'
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>LektorenPlan Prototyp · Pfarreiengemeinschaft Bad Godesberg</string>
|
||||
<string>LektorenPlan 0.9 · Build __BUILD_DISPLAY_DATE__ · Pfarreiengemeinschaft Bad Godesberg</string>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST
|
||||
|
||||
BUILD_ISO_DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
BUILD_DISPLAY_DATE="$(date +"%d.%m.%Y, %H:%M")"
|
||||
/usr/bin/sed -i '' \
|
||||
-e "s/__BUILD_ISO_DATE__/$BUILD_ISO_DATE/" \
|
||||
-e "s/__BUILD_DISPLAY_DATE__/$BUILD_DISPLAY_DATE/" \
|
||||
"$CONTENTS/Info.plist"
|
||||
|
||||
echo "Fertig: $APP"
|
||||
@@ -7,14 +7,21 @@ struct TimelineRangePicker: View {
|
||||
@State private var draftEnd = DayMath.today()
|
||||
@State private var initialized = false
|
||||
@State private var dragOrigin: DayRange?
|
||||
@State private var dragBounds: DayRange?
|
||||
@State private var zoom: Double = 1
|
||||
@State private var viewportCenter: Date?
|
||||
@State private var startCalendarVisible = false
|
||||
@State private var endCalendarVisible = false
|
||||
|
||||
private let minDays = 7
|
||||
|
||||
var body: some View {
|
||||
let bounds = timelineBounds
|
||||
VStack(spacing: 12) {
|
||||
header(bounds: bounds)
|
||||
timeline(bounds: bounds)
|
||||
let fullBounds = calendarBounds
|
||||
let visible = dragBounds ?? visibleBounds(in: fullBounds)
|
||||
VStack(spacing: 10) {
|
||||
header(bounds: fullBounds)
|
||||
rangeControls
|
||||
timeline(bounds: visible)
|
||||
.frame(height: 64)
|
||||
footer
|
||||
}
|
||||
@@ -33,15 +40,21 @@ struct TimelineRangePicker: View {
|
||||
guard !initialized else { return }
|
||||
draftStart = model.range.start
|
||||
draftEnd = model.range.end
|
||||
viewportCenter = midpoint(draftRange)
|
||||
initialized = true
|
||||
}
|
||||
.onChange(of: model.range) { _, newValue in
|
||||
draftStart = newValue.start
|
||||
draftEnd = newValue.end
|
||||
viewportCenter = midpoint(newValue)
|
||||
}
|
||||
.onChange(of: zoom) { _, _ in
|
||||
dragBounds = nil
|
||||
viewportCenter = midpoint(draftRange)
|
||||
}
|
||||
}
|
||||
|
||||
private var timelineBounds: DayRange {
|
||||
private var calendarBounds: DayRange {
|
||||
let currentYear = DayMath.year(DayMath.today())
|
||||
let firstYear = min(currentYear - 1, DayMath.year(draftStart) - 1)
|
||||
let lastYear = max(currentYear + 2, DayMath.year(draftEnd) + 1)
|
||||
@@ -50,6 +63,31 @@ struct TimelineRangePicker: View {
|
||||
return DayRange(start: start, end: end)
|
||||
}
|
||||
|
||||
private func visibleBounds(in full: DayRange) -> DayRange {
|
||||
guard zoom > 1.01 else { return full }
|
||||
let center = viewportCenter ?? midpoint(draftRange)
|
||||
let selectionDays = max(1, draftRange.dayCount)
|
||||
let idealSpan = Int((Double(max(1, full.dayCount)) / zoom).rounded())
|
||||
let span = min(full.dayCount, max(minDays + 14, max(selectionDays + 28, idealSpan)))
|
||||
var start = DayMath.adding(days: -(span / 2), to: center)
|
||||
var end = DayMath.adding(days: span - 1, to: start)
|
||||
if start < full.start {
|
||||
start = full.start
|
||||
end = DayMath.adding(days: span - 1, to: start)
|
||||
}
|
||||
if end > full.end {
|
||||
end = full.end
|
||||
start = DayMath.adding(days: -(span - 1), to: end)
|
||||
}
|
||||
if start < full.start { start = full.start }
|
||||
return DayRange(start: start, end: end)
|
||||
}
|
||||
|
||||
private func midpoint(_ range: DayRange) -> Date {
|
||||
let days = max(0, DayMath.daysBetween(range.start, range.end))
|
||||
return DayMath.adding(days: days / 2, to: range.start)
|
||||
}
|
||||
|
||||
private func header(bounds: DayRange) -> some View {
|
||||
HStack(alignment: .center, spacing: 12) {
|
||||
HStack(spacing: 7) {
|
||||
@@ -123,6 +161,151 @@ struct TimelineRangePicker: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var rangeControls: some View {
|
||||
HStack(spacing: 10) {
|
||||
dateField(
|
||||
label: "Beginn",
|
||||
date: draftStart,
|
||||
selection: startBinding,
|
||||
isPresented: $startCalendarVisible
|
||||
)
|
||||
Text("bis")
|
||||
.font(.system(size: 9.5, weight: .medium, design: .rounded))
|
||||
.foregroundStyle(LP.inkTertiary)
|
||||
dateField(
|
||||
label: "Ende",
|
||||
date: draftEnd,
|
||||
selection: endBinding,
|
||||
isPresented: $endCalendarVisible
|
||||
)
|
||||
|
||||
Spacer(minLength: 12)
|
||||
|
||||
zoomControl
|
||||
}
|
||||
}
|
||||
|
||||
private func dateField(
|
||||
label: String,
|
||||
date: Date,
|
||||
selection: Binding<Date>,
|
||||
isPresented: Binding<Bool>
|
||||
) -> some View {
|
||||
Button {
|
||||
isPresented.wrappedValue.toggle()
|
||||
} label: {
|
||||
HStack(spacing: 6) {
|
||||
Text(label)
|
||||
.font(.system(size: 9, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(LP.inkTertiary)
|
||||
Text(DayMath.mediumString(date))
|
||||
.font(.system(size: 10, weight: .medium))
|
||||
.foregroundStyle(LP.ink)
|
||||
.monospacedDigit()
|
||||
Image(systemName: "calendar")
|
||||
.font(.system(size: 9, weight: .semibold))
|
||||
.foregroundStyle(LP.accent)
|
||||
}
|
||||
.padding(.horizontal, 8)
|
||||
.padding(.vertical, 4)
|
||||
.background(RoundedRectangle(cornerRadius: 7).fill(LP.cardMuted))
|
||||
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.7))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.popover(isPresented: isPresented, arrowEdge: .bottom) {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text(label)
|
||||
.font(.system(size: 10, weight: .bold, design: .rounded))
|
||||
.foregroundStyle(LP.inkSecondary)
|
||||
DatePicker("", selection: selection, displayedComponents: .date)
|
||||
.datePickerStyle(.graphical)
|
||||
.labelsHidden()
|
||||
.onChange(of: selection.wrappedValue) { _, _ in
|
||||
isPresented.wrappedValue = false
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
}
|
||||
.help("\(label) über den Kalender wählen")
|
||||
}
|
||||
|
||||
private var startBinding: Binding<Date> {
|
||||
Binding(
|
||||
get: { draftStart },
|
||||
set: { newValue in
|
||||
let maxStart = DayMath.adding(days: -(minDays - 1), to: draftEnd)
|
||||
let clamped = min(max(DayMath.normalize(newValue), calendarBounds.start), maxStart)
|
||||
draftStart = clamped
|
||||
viewportCenter = midpoint(draftRange)
|
||||
model.setRange(draftRange)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private var endBinding: Binding<Date> {
|
||||
Binding(
|
||||
get: { draftEnd },
|
||||
set: { newValue in
|
||||
let minEnd = DayMath.adding(days: minDays - 1, to: draftStart)
|
||||
let clamped = max(min(DayMath.normalize(newValue), calendarBounds.end), minEnd)
|
||||
draftEnd = clamped
|
||||
viewportCenter = midpoint(draftRange)
|
||||
model.setRange(draftRange)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private var zoomControl: some View {
|
||||
HStack(spacing: 6) {
|
||||
Button {
|
||||
zoom = max(1, zoom - 1)
|
||||
} label: {
|
||||
Image(systemName: "minus.magnifyingglass")
|
||||
.font(.system(size: 9, weight: .semibold))
|
||||
.foregroundStyle(LP.inkTertiary)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Herauszoomen")
|
||||
.disabled(zoom <= 1.01)
|
||||
|
||||
Slider(value: $zoom, in: 1...16, step: 0.5)
|
||||
.tint(LP.accent)
|
||||
.frame(width: 110)
|
||||
|
||||
Button {
|
||||
zoom = min(16, zoom + 1)
|
||||
} label: {
|
||||
Image(systemName: "plus.magnifyingglass")
|
||||
.font(.system(size: 9, weight: .semibold))
|
||||
.foregroundStyle(LP.inkTertiary)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Hineinzoomen")
|
||||
.disabled(zoom >= 15.99)
|
||||
|
||||
Text(String(format: "%.1f×", zoom))
|
||||
.font(.system(size: 9, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(LP.inkSecondary)
|
||||
.frame(width: 32, alignment: .trailing)
|
||||
.monospacedDigit()
|
||||
Button {
|
||||
zoom = 1
|
||||
} label: {
|
||||
Image(systemName: "arrow.counterclockwise")
|
||||
.font(.system(size: 9, weight: .semibold))
|
||||
.foregroundStyle(LP.inkTertiary)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Zoom zurücksetzen")
|
||||
.disabled(zoom <= 1.01)
|
||||
}
|
||||
.padding(.horizontal, 8)
|
||||
.padding(.vertical, 4)
|
||||
.background(RoundedRectangle(cornerRadius: 7).fill(LP.cardMuted))
|
||||
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.7))
|
||||
.help("Globale Zeitskala zoomen")
|
||||
}
|
||||
|
||||
private func timeline(bounds: DayRange) -> some View {
|
||||
GeometryReader { geo in
|
||||
let width = geo.size.width
|
||||
@@ -179,8 +362,8 @@ struct TimelineRangePicker: View {
|
||||
}
|
||||
}
|
||||
|
||||
// Month labels around selection
|
||||
if width > 500 {
|
||||
// Date labels around selection (only when they do not overlap)
|
||||
if width > 500, xEnd - xStart >= 120 {
|
||||
Text(DayMath.mediumString(draftStart))
|
||||
.font(.system(size: 9, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(LP.accent)
|
||||
@@ -226,7 +409,7 @@ struct TimelineRangePicker: View {
|
||||
Text("\(Int(model.stats.coverageRate * 100)) % besetzt")
|
||||
.foregroundStyle(model.stats.openSlots == 0 ? LP.success : LP.open)
|
||||
Spacer()
|
||||
Text("Ziehen oder Zeitmarke wählen")
|
||||
Text("Ziehen, zoomen oder Datum wählen")
|
||||
.foregroundStyle(LP.inkTertiary)
|
||||
}
|
||||
.font(.system(size: 9.5, weight: .medium, design: .rounded))
|
||||
@@ -275,6 +458,8 @@ struct TimelineRangePicker: View {
|
||||
.opacity(0.5)
|
||||
}
|
||||
.shadow(color: color.opacity(0.35), radius: 4, y: 2)
|
||||
.frame(width: 24, height: 48)
|
||||
.contentShape(Rectangle())
|
||||
.help(help)
|
||||
}
|
||||
|
||||
@@ -285,6 +470,7 @@ struct TimelineRangePicker: View {
|
||||
.onChanged { value in
|
||||
if dragOrigin == nil {
|
||||
dragOrigin = DayRange(start: draftStart, end: draftEnd)
|
||||
dragBounds = bounds
|
||||
}
|
||||
guard let origin = dragOrigin else { return }
|
||||
let dayDelta = Int((value.translation.width / max(1, width)) * totalDays)
|
||||
@@ -304,6 +490,8 @@ struct TimelineRangePicker: View {
|
||||
}
|
||||
.onEnded { _ in
|
||||
dragOrigin = nil
|
||||
dragBounds = nil
|
||||
viewportCenter = midpoint(draftRange)
|
||||
model.setRange(draftRange)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,14 +43,22 @@ struct AppCommands: Commands {
|
||||
}
|
||||
.keyboardShortcut("i", modifiers: [.command, .shift])
|
||||
Divider()
|
||||
Button("PDF-Vorschau…") {
|
||||
model.createPDFPreview()
|
||||
Button("PDF-Vorschau (übersichtlich)…") {
|
||||
model.createPDFPreview(variant: .full)
|
||||
}
|
||||
.keyboardShortcut("p", modifiers: [.command, .shift])
|
||||
Button("Drucken…") {
|
||||
model.printPDF()
|
||||
Button("PDF-Vorschau (kompakte Liste)…") {
|
||||
model.createPDFPreview(variant: .compact)
|
||||
}
|
||||
.keyboardShortcut("l", modifiers: [.command, .shift])
|
||||
Button("Drucken (übersichtlich)…") {
|
||||
model.printPDF(variant: .full)
|
||||
}
|
||||
.keyboardShortcut("p", modifiers: .command)
|
||||
Button("Drucken (kompakte Liste)…") {
|
||||
model.printPDF(variant: .compact)
|
||||
}
|
||||
.keyboardShortcut("p", modifiers: [.command, .option])
|
||||
}
|
||||
|
||||
CommandMenu("Planung") {
|
||||
|
||||
@@ -260,6 +260,7 @@ enum PlanPDFRenderer {
|
||||
var height: CGFloat = 5
|
||||
for service in services {
|
||||
height += 12
|
||||
if service.service.location != nil { height += 9 }
|
||||
for role in Role.allCases where service.service.requiredCount(for: role) > 0 {
|
||||
height += 9
|
||||
}
|
||||
@@ -373,6 +374,17 @@ enum PlanPDFRenderer {
|
||||
)
|
||||
serviceY += 11
|
||||
|
||||
if let location = service.service.location {
|
||||
drawText(
|
||||
location,
|
||||
in: CGRect(x: x + 7, y: serviceY, width: churchWidth - 12, height: 9),
|
||||
font: sans(6.5, weight: .medium),
|
||||
color: burgundy,
|
||||
maxLines: 1
|
||||
)
|
||||
serviceY += 9
|
||||
}
|
||||
|
||||
for role in Role.allCases where service.service.requiredCount(for: role) > 0 {
|
||||
let names = service.assignments(for: role).compactMap { people[$0.personID]?.fullName }
|
||||
let prefix = role == .lector ? "L" : "K"
|
||||
|
||||
@@ -111,6 +111,26 @@ struct PDFPreview: Identifiable {
|
||||
var data: Data
|
||||
var title: String
|
||||
var filename: String
|
||||
var formatLabel: String
|
||||
}
|
||||
|
||||
enum PlanPDFVariant {
|
||||
case full
|
||||
case compact
|
||||
|
||||
var formatLabel: String {
|
||||
switch self {
|
||||
case .full: "A4 quer · Kirchenspalten"
|
||||
case .compact: "A4 hoch · kompakte Liste"
|
||||
}
|
||||
}
|
||||
|
||||
var filenameComponent: String {
|
||||
switch self {
|
||||
case .full: "Plan"
|
||||
case .compact: "Liste"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CandidateSuggestion: Identifiable {
|
||||
@@ -162,6 +182,7 @@ final class PlanModel: ObservableObject {
|
||||
@Published var pdfPreview: PDFPreview?
|
||||
@Published var databasePath: String
|
||||
@Published var startupWarning: String?
|
||||
@Published var isResettingData = false
|
||||
|
||||
private var toastTask: Task<Void, Never>?
|
||||
|
||||
@@ -302,6 +323,8 @@ final class PlanModel: ObservableObject {
|
||||
if row.liturgicalDay?.readings.shortLabel.lowercased().contains(query) == true { return true }
|
||||
for service in row.services {
|
||||
if service.church.name.lowercased().contains(query) { return true }
|
||||
if let location = service.service.location,
|
||||
location.lowercased().contains(query) { return true }
|
||||
if service.service.title.lowercased().contains(query) { return true }
|
||||
for assignment in service.assignments {
|
||||
if let person = peopleByID[assignment.personID],
|
||||
@@ -418,26 +441,47 @@ final class PlanModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
func candidateSuggestions(for service: ServiceOccurrence, role: Role) -> [CandidateSuggestion] {
|
||||
func candidateSuggestions(
|
||||
for service: ServiceOccurrence,
|
||||
role: Role,
|
||||
ignorePreferredWeekdays: Bool = false
|
||||
) -> [CandidateSuggestion] {
|
||||
let rangeAssignments = assignments
|
||||
let monthKey = DayMath.monthKey(service.date)
|
||||
let serviceDateByID = Dictionary(uniqueKeysWithValues: services.map { ($0.id, $0) })
|
||||
|
||||
var monthlyCounts: [String: Int] = [:]
|
||||
var totalCounts: [String: Int] = [:]
|
||||
var dayCounts: [String: Int] = [:]
|
||||
var dayServices: [String: Set<String>] = [:]
|
||||
for assignment in rangeAssignments {
|
||||
guard let assignedService = serviceDateByID[assignment.serviceID] else { continue }
|
||||
monthlyCounts["\(assignment.personID)|\(DayMath.monthKey(assignedService.date))", default: 0] += 1
|
||||
totalCounts[assignment.personID, default: 0] += 1
|
||||
dayCounts["\(assignment.personID)|\(assignedService.dateKey)", default: 0] += 1
|
||||
dayServices["\(assignment.personID)|\(assignedService.dateKey)", default: []].insert(assignment.serviceID)
|
||||
}
|
||||
|
||||
let assignedToService = Set(assignments.filter { $0.serviceID == service.id }.map(\.personID))
|
||||
// Lector and helper do not exclude each other: a person may be suggested
|
||||
// for the complementary role even when already serving this service.
|
||||
// Read the service assignments directly so this also works when the
|
||||
// service is outside the currently loaded range.
|
||||
let serviceAssignments = (try? db.assignments(serviceIDs: [service.id]))
|
||||
?? assignments.filter { $0.serviceID == service.id }
|
||||
var assignedRolesByPerson: [String: Set<Role>] = [:]
|
||||
for assignment in serviceAssignments {
|
||||
assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role)
|
||||
}
|
||||
let weekday = DayMath.weekday(service.date)
|
||||
|
||||
return people
|
||||
.filter { $0.active && $0.canFill(role) && !assignedToService.contains($0.id) }
|
||||
let eligiblePeople = people.filter { person in
|
||||
guard person.active, person.canFill(role) else { return false }
|
||||
return !(assignedRolesByPerson[person.id]?.contains(role) ?? false)
|
||||
}
|
||||
// Only prefer a dual-role assignment while the person is not already
|
||||
// noticeably ahead of others. Otherwise fairness wins.
|
||||
let minimumTotal = eligiblePeople.map { totalCounts[$0.id, default: 0] }.min() ?? 0
|
||||
let fairnessSlack = 1
|
||||
|
||||
return eligiblePeople
|
||||
.map { person in
|
||||
var warnings: [String] = []
|
||||
var blocked = false
|
||||
@@ -445,7 +489,9 @@ final class PlanModel: ObservableObject {
|
||||
warnings.append("abwesend")
|
||||
blocked = true
|
||||
}
|
||||
if !person.preferredWeekdays.isEmpty && !person.preferredWeekdays.contains(weekday) {
|
||||
if !ignorePreferredWeekdays,
|
||||
!person.preferredWeekdays.isEmpty,
|
||||
!person.preferredWeekdays.contains(weekday) {
|
||||
warnings.append("Einsatztag passt nicht")
|
||||
blocked = true
|
||||
}
|
||||
@@ -453,12 +499,24 @@ final class PlanModel: ObservableObject {
|
||||
warnings.append("Monatslimit")
|
||||
blocked = true
|
||||
}
|
||||
if dayCounts["\(person.id)|\(service.dateKey)", default: 0] > 0 {
|
||||
let servicesThisDay = dayServices["\(person.id)|\(service.dateKey)", default: []]
|
||||
if !servicesThisDay.isEmpty, !servicesThisDay.isSubset(of: [service.id]) {
|
||||
warnings.append("bereits an diesem Tag")
|
||||
blocked = true
|
||||
}
|
||||
let total = totalCounts[person.id, default: 0]
|
||||
let withinFairnessReach = total - minimumTotal <= fairnessSlack
|
||||
var score = 0.0
|
||||
var preferred = false
|
||||
if withinFairnessReach, assignedRolesByPerson[person.id]?.contains(role.complementary) == true {
|
||||
score += 14
|
||||
preferred = true
|
||||
} else if withinFairnessReach,
|
||||
service.rolesNeeded.count > 1,
|
||||
person.roles.contains(where: { $0 != role && service.requiredCount(for: $0) > 0 }) {
|
||||
score += 14
|
||||
preferred = true
|
||||
}
|
||||
if person.preferredChurchIDs.contains(service.churchID) {
|
||||
score += 8
|
||||
preferred = true
|
||||
@@ -476,7 +534,7 @@ final class PlanModel: ObservableObject {
|
||||
preferred = true
|
||||
}
|
||||
}
|
||||
score -= Double(totalCounts[person.id, default: 0]) * 1.4
|
||||
score -= Double(total) * 1.4
|
||||
if absences.contains(where: { $0.personID == person.id && $0.overlaps(service.date) }) {
|
||||
score -= 100
|
||||
}
|
||||
@@ -780,18 +838,32 @@ final class PlanModel: ObservableObject {
|
||||
|
||||
// MARK: - PDF & print
|
||||
|
||||
func createPDFPreview() {
|
||||
let data = PlanPDFRenderer.render(
|
||||
range: range,
|
||||
rows: rows,
|
||||
churches: churches,
|
||||
people: peopleByID,
|
||||
generatedAt: Date()
|
||||
)
|
||||
func createPDFPreview(variant: PlanPDFVariant = .full) {
|
||||
let data: Data
|
||||
switch variant {
|
||||
case .full:
|
||||
data = PlanPDFRenderer.render(
|
||||
range: range,
|
||||
rows: rows,
|
||||
churches: churches,
|
||||
people: peopleByID,
|
||||
generatedAt: Date()
|
||||
)
|
||||
case .compact:
|
||||
data = CompactPlanPDFRenderer.render(
|
||||
range: range,
|
||||
rows: rows,
|
||||
people: peopleByID,
|
||||
generatedAt: Date()
|
||||
)
|
||||
}
|
||||
pdfPreview = PDFPreview(
|
||||
data: data,
|
||||
title: "Lektorenplan \(range.shortTitle)",
|
||||
filename: "LektorenPlan_\(DayMath.key(range.start))_\(DayMath.key(range.end)).pdf"
|
||||
title: variant == .compact
|
||||
? "Gottesdienstliste \(range.shortTitle)"
|
||||
: "Lektorenplan \(range.shortTitle)",
|
||||
filename: "LektorenPlan_\(variant.filenameComponent)_\(DayMath.key(range.start))_\(DayMath.key(range.end)).pdf",
|
||||
formatLabel: variant.formatLabel
|
||||
)
|
||||
}
|
||||
|
||||
@@ -811,21 +883,34 @@ final class PlanModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
func printPDF(data: Data? = nil) {
|
||||
let pdfData = data ?? PlanPDFRenderer.render(
|
||||
range: range,
|
||||
rows: rows,
|
||||
churches: churches,
|
||||
people: peopleByID,
|
||||
generatedAt: Date()
|
||||
)
|
||||
func printPDF(data: Data? = nil, variant: PlanPDFVariant = .full) {
|
||||
let pdfData = data ?? {
|
||||
switch variant {
|
||||
case .full:
|
||||
return PlanPDFRenderer.render(
|
||||
range: range,
|
||||
rows: rows,
|
||||
churches: churches,
|
||||
people: peopleByID,
|
||||
generatedAt: Date()
|
||||
)
|
||||
case .compact:
|
||||
return CompactPlanPDFRenderer.render(
|
||||
range: range,
|
||||
rows: rows,
|
||||
people: peopleByID,
|
||||
generatedAt: Date()
|
||||
)
|
||||
}
|
||||
}()
|
||||
guard let document = PDFDocument(data: pdfData) else {
|
||||
alertTitle = "Drucken nicht möglich"
|
||||
alertMessage = "Das PDF konnte nicht erzeugt werden."
|
||||
return
|
||||
}
|
||||
let info = NSPrintInfo.shared.copy() as? NSPrintInfo ?? NSPrintInfo.shared
|
||||
info.orientation = .landscape
|
||||
let bounds = document.page(at: 0)?.bounds(for: .mediaBox) ?? .zero
|
||||
info.orientation = bounds.width > bounds.height ? .landscape : .portrait
|
||||
info.topMargin = 0
|
||||
info.bottomMargin = 0
|
||||
info.leftMargin = 0
|
||||
@@ -840,13 +925,43 @@ final class PlanModel: ObservableObject {
|
||||
// MARK: - Demo
|
||||
|
||||
func resetDemoData() {
|
||||
do {
|
||||
try db.resetDemoData()
|
||||
loadAll()
|
||||
showToast("Demo-Daten neu aufgebaut.", kind: .success)
|
||||
} catch {
|
||||
alertTitle = "Demo-Daten konnten nicht zurückgesetzt werden"
|
||||
alertMessage = error.localizedDescription
|
||||
rebuildContent(deleteOnly: false)
|
||||
}
|
||||
|
||||
func deleteAllData() {
|
||||
rebuildContent(deleteOnly: true)
|
||||
}
|
||||
|
||||
private func rebuildContent(deleteOnly: Bool) {
|
||||
guard !isResettingData else { return }
|
||||
isResettingData = true
|
||||
let database = db
|
||||
Task {
|
||||
do {
|
||||
try await Task.detached(priority: .userInitiated) {
|
||||
if deleteOnly {
|
||||
try database.deleteAllData()
|
||||
} else {
|
||||
try database.resetDemoData()
|
||||
}
|
||||
}.value
|
||||
|
||||
range = .quarter(containing: DayMath.today())
|
||||
db.setSetting("rangeStart", value: DayMath.key(range.start))
|
||||
db.setSetting("rangeEnd", value: DayMath.key(range.end))
|
||||
loadAll()
|
||||
isResettingData = false
|
||||
showToast(
|
||||
deleteOnly ? "Alle Daten wurden gelöscht." : "Demo-Daten neu aufgebaut.",
|
||||
kind: .success
|
||||
)
|
||||
} catch {
|
||||
isResettingData = false
|
||||
alertTitle = deleteOnly
|
||||
? "Daten konnten nicht gelöscht werden"
|
||||
: "Demo-Daten konnten nicht zurückgesetzt werden"
|
||||
alertMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -226,7 +226,7 @@ private struct SidebarView: View {
|
||||
.foregroundStyle(LP.inkTertiary.opacity(0.85))
|
||||
.underline()
|
||||
}
|
||||
Text("Prototyp 0.1 · Erzbistum Köln")
|
||||
Text("Version \(AppMetadata.version) · Erzbistum Köln")
|
||||
.font(.system(size: 7.5, weight: .regular))
|
||||
.foregroundStyle(LP.inkTertiary.opacity(0.7))
|
||||
}
|
||||
|
||||
@@ -11,18 +11,57 @@ enum SnapshotCapture {
|
||||
let environment = ProcessInfo.processInfo.environment
|
||||
let wantsSnapshot = environment["LP_SNAPSHOT"] != nil
|
||||
let wantsPDF = environment["LP_PDF"] != nil
|
||||
let resetReportPath = environment["LP_RESET_DEMO"]
|
||||
|
||||
guard wantsSnapshot || wantsPDF || resetReportPath != nil else { return }
|
||||
|
||||
if let resetReportPath {
|
||||
// End-to-end check of the settings recovery flow: run the real model
|
||||
// action, wait until the async rebuild finishes, then report counts.
|
||||
switch environment["LP_RESET_MODE"] {
|
||||
case "delete":
|
||||
model.deleteAllData()
|
||||
case "none":
|
||||
break
|
||||
default:
|
||||
model.resetDemoData()
|
||||
}
|
||||
let deadline = Date().addingTimeInterval(60)
|
||||
while model.isResettingData && Date() < deadline {
|
||||
try? await Task.sleep(nanoseconds: 100_000_000)
|
||||
}
|
||||
let report = """
|
||||
churches=\(model.churches.count)
|
||||
people=\(model.people.count)
|
||||
services=\(model.services.count)
|
||||
isResetting=\(model.isResettingData)
|
||||
alert=\(model.alertMessage ?? "none")
|
||||
"""
|
||||
try? report.write(toFile: resetReportPath, atomically: true, encoding: .utf8)
|
||||
NSApplication.shared.terminate(nil)
|
||||
return
|
||||
}
|
||||
|
||||
guard wantsSnapshot || wantsPDF else { return }
|
||||
try? await Task.sleep(nanoseconds: 1_500_000_000)
|
||||
|
||||
if let pdfPath = environment["LP_PDF"] {
|
||||
let data = PlanPDFRenderer.render(
|
||||
range: model.range,
|
||||
rows: model.rows,
|
||||
churches: model.churches,
|
||||
people: model.peopleByID,
|
||||
generatedAt: Date()
|
||||
)
|
||||
let data: Data
|
||||
if environment["LP_PDF_VARIANT"] == "compact" {
|
||||
data = CompactPlanPDFRenderer.render(
|
||||
range: model.range,
|
||||
rows: model.rows,
|
||||
people: model.peopleByID,
|
||||
generatedAt: Date()
|
||||
)
|
||||
} else {
|
||||
data = PlanPDFRenderer.render(
|
||||
range: model.range,
|
||||
rows: model.rows,
|
||||
churches: model.churches,
|
||||
people: model.peopleByID,
|
||||
generatedAt: Date()
|
||||
)
|
||||
}
|
||||
try? data.write(to: URL(fileURLWithPath: pdfPath))
|
||||
}
|
||||
|
||||
|
||||
@@ -274,7 +274,7 @@ struct PersonMiniChip: View {
|
||||
var body: some View {
|
||||
HStack(spacing: 4) {
|
||||
Avatar(initials: person.initials, color: color, size: 18)
|
||||
Text(person.firstNameWithInitial)
|
||||
Text(person.abbreviatedName)
|
||||
.font(.system(size: 10.5, weight: .medium))
|
||||
.foregroundStyle(LP.ink)
|
||||
.lineLimit(1)
|
||||
|
||||
@@ -28,7 +28,7 @@ struct PDFPreviewSheet: View {
|
||||
Text(preview.title)
|
||||
.font(LP.serifHeadline)
|
||||
.foregroundStyle(LP.ink)
|
||||
Text("\(document?.pageCount ?? 0) Seiten · A4 quer · bereit zum Drucken")
|
||||
Text("\(document?.pageCount ?? 0) Seiten · \(preview.formatLabel) · bereit zum Drucken")
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(LP.inkSecondary)
|
||||
}
|
||||
|
||||
@@ -54,9 +54,14 @@ struct PlanningView: View {
|
||||
.disabled(model.isSyncing)
|
||||
|
||||
SecondaryActionButton(title: "PDF", icon: "doc.richtext") {
|
||||
model.createPDFPreview()
|
||||
model.createPDFPreview(variant: .full)
|
||||
}
|
||||
.help("Planung als PDF ansehen, sichern oder drucken")
|
||||
.help("Übersichtlichen Plan als PDF ansehen, sichern oder drucken (A4 quer)")
|
||||
|
||||
SecondaryActionButton(title: "Liste", icon: "list.bullet.rectangle") {
|
||||
model.createPDFPreview(variant: .compact)
|
||||
}
|
||||
.help("Kompakte Gottesdienstliste als PDF ansehen, sichern oder drucken (A4 hoch)")
|
||||
|
||||
Menu {
|
||||
Button {
|
||||
@@ -164,39 +169,50 @@ private struct CalendarTable: View {
|
||||
let minimum = horizontalPadding * 2 + dateWidth + liturgyWidth + churchMinWidth * 4 + gap * 5
|
||||
let width = max(geo.size.width, minimum)
|
||||
let churchWidth = (width - horizontalPadding * 2 - dateWidth - liturgyWidth - gap * 5) / 4
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
VStack(spacing: 0) {
|
||||
columnHeader(churchWidth: churchWidth)
|
||||
Hairline()
|
||||
if model.filteredRows.isEmpty {
|
||||
EmptyStateView(
|
||||
icon: "calendar",
|
||||
title: "Keine Tage im Filter",
|
||||
message: "Für diesen Zeitraum und Filter sind keine Einträge vorhanden."
|
||||
)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
ScrollView(.vertical) {
|
||||
LazyVStack(spacing: 0, pinnedViews: []) {
|
||||
ForEach(monthGroups) { group in
|
||||
monthHeader(group, churchWidth: churchWidth)
|
||||
ForEach(group.rows) { row in
|
||||
DayRow(
|
||||
row: row,
|
||||
churchWidth: churchWidth,
|
||||
dateWidth: dateWidth,
|
||||
liturgyWidth: liturgyWidth,
|
||||
gap: gap,
|
||||
horizontalPadding: horizontalPadding
|
||||
)
|
||||
if model.churches.isEmpty {
|
||||
EmptyStateView(
|
||||
icon: "building.columns",
|
||||
title: "Keine Daten vorhanden",
|
||||
message: "Es sind keine Kirchen und Personen hinterlegt. Stellen Sie die Demo-Daten wieder her oder importieren Sie eine Sicherung.",
|
||||
actionTitle: "Demo-Daten wiederherstellen",
|
||||
action: { model.resetDemoData() }
|
||||
)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
VStack(spacing: 0) {
|
||||
columnHeader(churchWidth: churchWidth)
|
||||
Hairline()
|
||||
if model.filteredRows.isEmpty {
|
||||
EmptyStateView(
|
||||
icon: "calendar",
|
||||
title: "Keine Tage im Filter",
|
||||
message: "Für diesen Zeitraum und Filter sind keine Einträge vorhanden."
|
||||
)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
ScrollView(.vertical) {
|
||||
LazyVStack(spacing: 0, pinnedViews: []) {
|
||||
ForEach(monthGroups) { group in
|
||||
monthHeader(group, churchWidth: churchWidth)
|
||||
ForEach(group.rows) { row in
|
||||
DayRow(
|
||||
row: row,
|
||||
churchWidth: churchWidth,
|
||||
dateWidth: dateWidth,
|
||||
liturgyWidth: liturgyWidth,
|
||||
gap: gap,
|
||||
horizontalPadding: horizontalPadding
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.bottom, 10)
|
||||
}
|
||||
.padding(.bottom, 10)
|
||||
}
|
||||
}
|
||||
.frame(width: width, height: geo.size.height, alignment: .top)
|
||||
}
|
||||
.frame(width: width, height: geo.size.height, alignment: .top)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -510,6 +526,17 @@ private struct DayRow: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
.overlay(alignment: .topTrailing) {
|
||||
Button {
|
||||
model.specialServiceEditor = SpecialServiceRequest(churchID: nil, date: row.date)
|
||||
} label: {
|
||||
Image(systemName: "plus.circle.fill")
|
||||
.font(.system(size: 11, weight: .semibold))
|
||||
.foregroundStyle(LP.burgundy.opacity(0.62))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Sondergottesdienst an diesem Tag hinzufügen")
|
||||
}
|
||||
}
|
||||
|
||||
private var liturgyCell: some View {
|
||||
@@ -634,6 +661,12 @@ private struct ServiceCard: View {
|
||||
.background(Capsule().fill(LP.openSoft))
|
||||
}
|
||||
}
|
||||
if let location = service.service.location {
|
||||
Text(location)
|
||||
.font(.system(size: 7.5, weight: .medium))
|
||||
.foregroundStyle(LP.burgundy)
|
||||
.lineLimit(1)
|
||||
}
|
||||
ForEach(Role.allCases) { role in
|
||||
if service.service.requiredCount(for: role) > 0 {
|
||||
roleLine(role: role)
|
||||
@@ -695,7 +728,7 @@ private struct ServiceCard: View {
|
||||
|
||||
private var helpText: String {
|
||||
var lines = [
|
||||
"\(service.church.name) · \(DayMath.longString(service.service.date)) · \(service.service.timeLabel)",
|
||||
"\(service.service.placeName(church: service.church)) · \(DayMath.longString(service.service.date)) · \(service.service.timeLabel)",
|
||||
service.service.title
|
||||
]
|
||||
for role in Role.allCases {
|
||||
|
||||
@@ -8,6 +8,7 @@ struct ServiceDetailSheet: View {
|
||||
let serviceID: String
|
||||
|
||||
@State private var selectedRole: Role = .lector
|
||||
@State private var ignorePreferredWeekdays = false
|
||||
@State private var confirmDelete = false
|
||||
|
||||
private var item: ServiceWithAssignments? {
|
||||
@@ -112,7 +113,7 @@ struct ServiceDetailSheet: View {
|
||||
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
HStack(spacing: 6) {
|
||||
Text(item.church.name)
|
||||
Text(item.service.placeName(church: item.church))
|
||||
.font(.system(size: 10, weight: .bold, design: .rounded))
|
||||
.tracking(0.8)
|
||||
.foregroundStyle(churchColor)
|
||||
@@ -148,6 +149,14 @@ struct ServiceDetailSheet: View {
|
||||
.font(.system(size: 9, weight: .medium))
|
||||
.foregroundStyle(LP.inkTertiary)
|
||||
}
|
||||
Toggle(isOn: $ignorePreferredWeekdays) {
|
||||
Text("Präferenztage ignorieren")
|
||||
.font(.system(size: 9, weight: .medium))
|
||||
.foregroundStyle(LP.inkSecondary)
|
||||
}
|
||||
.toggleStyle(.switch)
|
||||
.controlSize(.mini)
|
||||
.help("Auch Personen anbieten, deren bevorzugte Einsatztage diesen Termin ausschließen. Ausschlusstermine bleiben gesperrt.")
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 22)
|
||||
@@ -342,7 +351,11 @@ struct ServiceDetailSheet: View {
|
||||
|
||||
Hairline()
|
||||
|
||||
let suggestions = model.candidateSuggestions(for: item.service, role: selectedRole)
|
||||
let suggestions = model.candidateSuggestions(
|
||||
for: item.service,
|
||||
role: selectedRole,
|
||||
ignorePreferredWeekdays: ignorePreferredWeekdays
|
||||
)
|
||||
if suggestions.isEmpty {
|
||||
EmptyStateView(
|
||||
icon: "person.crop.circle.badge.questionmark",
|
||||
|
||||
@@ -269,7 +269,10 @@ struct ServiceOrderView: View {
|
||||
.font(.system(size: 11, weight: .medium))
|
||||
.foregroundStyle(LP.ink)
|
||||
}
|
||||
Text([church?.name, service.notes].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))
|
||||
let place = church.map { service.placeName(church: $0) } ?? service.location ?? ""
|
||||
Text([place, service.notes]
|
||||
.filter { !$0.isEmpty }
|
||||
.joined(separator: " · "))
|
||||
.font(.system(size: 9))
|
||||
.foregroundStyle(LP.inkTertiary)
|
||||
.lineLimit(1)
|
||||
|
||||
@@ -7,7 +7,39 @@ struct SettingsView: View {
|
||||
@State private var autoSync = true
|
||||
@State private var respectWeekdays = true
|
||||
@State private var fairnessWeight = 2.2
|
||||
@State private var confirmReset = false
|
||||
@State private var dataAction: DataAction?
|
||||
|
||||
/// A single alert driver. Attaching two `.alert` modifiers to the same view
|
||||
/// is unreliable on macOS, so both destructive actions share one alert.
|
||||
private enum DataAction: String, Identifiable {
|
||||
case resetDemo
|
||||
case deleteAll
|
||||
|
||||
var id: String { rawValue }
|
||||
|
||||
var title: String {
|
||||
switch self {
|
||||
case .resetDemo: "Demo-Daten zurücksetzen?"
|
||||
case .deleteAll: "Alle Daten löschen?"
|
||||
}
|
||||
}
|
||||
|
||||
var confirmTitle: String {
|
||||
switch self {
|
||||
case .resetDemo: "Zurücksetzen"
|
||||
case .deleteAll: "Endgültig löschen"
|
||||
}
|
||||
}
|
||||
|
||||
var message: String {
|
||||
switch self {
|
||||
case .resetDemo:
|
||||
"Sämtliche Kirchen, Personen, Vorlagen, Gottesdienste und Einsätze werden gelöscht und mit den Demo-Daten neu aufgebaut. Dieser Schritt kann nicht rückgängig gemacht werden."
|
||||
case .deleteAll:
|
||||
"Kirchen, Personen, Abwesenheiten, Vorlagen, Gottesdienste, Einsätze und liturgische Tage werden entfernt. Die App bleibt leer, bis Sie Demo-Daten zurücksetzen oder eine Sicherung importieren."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 14) {
|
||||
@@ -40,17 +72,24 @@ struct SettingsView: View {
|
||||
.padding(.top, 30)
|
||||
.padding(.bottom, 18)
|
||||
.onAppear(perform: loadSettings)
|
||||
.confirmationDialog(
|
||||
"Demo-Daten zurücksetzen?",
|
||||
isPresented: $confirmReset,
|
||||
titleVisibility: .visible
|
||||
) {
|
||||
Button("Alle Daten zurücksetzen", role: .destructive) {
|
||||
model.resetDemoData()
|
||||
.alert(
|
||||
dataAction?.title ?? "",
|
||||
isPresented: Binding(
|
||||
get: { dataAction != nil },
|
||||
set: { if !$0 { dataAction = nil } }
|
||||
),
|
||||
presenting: dataAction
|
||||
) { action in
|
||||
Button("Abbrechen", role: .cancel) { dataAction = nil }
|
||||
Button(action.confirmTitle, role: .destructive) {
|
||||
switch action {
|
||||
case .resetDemo: model.resetDemoData()
|
||||
case .deleteAll: model.deleteAllData()
|
||||
}
|
||||
dataAction = nil
|
||||
}
|
||||
Button("Abbrechen", role: .cancel) {}
|
||||
} message: {
|
||||
Text("Sämtliche Kirchen, Personen, Vorlagen, Gottesdienste und Einsätze werden gelöscht und mit den Demo-Daten neu aufgebaut. Dieser Schritt kann nicht rückgängig gemacht werden.")
|
||||
} message: { action in
|
||||
Text(action.message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,7 +232,7 @@ struct SettingsView: View {
|
||||
Image(systemName: "info.circle")
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(LP.accent)
|
||||
Text("Harte Ausschlüsse: Abwesenheit, fehlende Rolle, Monatslimit, Doppelbelegung am selben Tag. Gesperrte Einsätze werden bei einer Neuplanung nie verändert.")
|
||||
Text("Harte Ausschlüsse: Abwesenheit, fehlende Rolle, Monatslimit, Doppelbelegung an verschiedenen Gottesdiensten am selben Tag. Lektor und Kommunionhelfer dürfen im selben Gottesdienst dieselbe Person sein. Gesperrte Einsätze werden bei einer Neuplanung nie verändert.")
|
||||
.font(.system(size: 9))
|
||||
.foregroundStyle(LP.inkSecondary)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
@@ -251,20 +290,51 @@ struct SettingsView: View {
|
||||
model.exportInteractive(scope: .resources)
|
||||
}
|
||||
Spacer()
|
||||
if model.isResettingData {
|
||||
ProgressView()
|
||||
.controlSize(.small)
|
||||
Text("Datenbank wird neu aufgebaut…")
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(LP.inkSecondary)
|
||||
}
|
||||
}
|
||||
|
||||
HStack(spacing: 9) {
|
||||
Button {
|
||||
confirmReset = true
|
||||
dataAction = .resetDemo
|
||||
} label: {
|
||||
HStack(spacing: 5) {
|
||||
Image(systemName: "arrow.counterclockwise")
|
||||
Text("Demo-Daten zurücksetzen")
|
||||
}
|
||||
.font(.system(size: 10.5, weight: .medium))
|
||||
.foregroundStyle(LP.accent)
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 5)
|
||||
.background(RoundedRectangle(cornerRadius: 7).fill(LP.accent.opacity(0.08)))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.disabled(model.isResettingData)
|
||||
.help("Löscht alle Inhalte und baut den Demo-Bestand neu auf")
|
||||
|
||||
Button {
|
||||
dataAction = .deleteAll
|
||||
} label: {
|
||||
HStack(spacing: 5) {
|
||||
Image(systemName: "trash")
|
||||
Text("Alle Daten löschen")
|
||||
}
|
||||
.font(.system(size: 10.5, weight: .medium))
|
||||
.foregroundStyle(LP.danger)
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 5)
|
||||
.background(RoundedRectangle(cornerRadius: 7).fill(LP.danger.opacity(0.08)))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.disabled(model.isResettingData)
|
||||
.help("Entfernt alle Inhalte, ohne Demo-Daten neu anzulegen")
|
||||
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -287,7 +357,10 @@ struct SettingsView: View {
|
||||
Text("LektorenPlan")
|
||||
.font(LP.serifHeadline)
|
||||
.foregroundStyle(LP.ink)
|
||||
Text("Prototyp 0.1 · Pfarreiengemeinschaft Bad Godesberg · Erzbistum Köln")
|
||||
Text("Version \(AppMetadata.version) · Build \(AppMetadata.buildDateLabel)")
|
||||
.font(.system(size: 9.5, weight: .medium))
|
||||
.foregroundStyle(LP.inkSecondary)
|
||||
Text("Pfarreiengemeinschaft Bad Godesberg · Erzbistum Köln")
|
||||
.font(.system(size: 9.5))
|
||||
.foregroundStyle(LP.inkSecondary)
|
||||
Text("Geplant werden Lektoren und Kommunionhelfer für St. Andreas, St. Evergislus, Herz Jesu und St. Hildegard. Liturgische Daten: www.eucharistiefeier.de (fair use). Alle Personen- und Plandaten in dieser Demo sind fiktiv.")
|
||||
|
||||
@@ -8,6 +8,7 @@ struct SpecialServiceSheet: View {
|
||||
let request: SpecialServiceRequest
|
||||
|
||||
@State private var churchID = ""
|
||||
@State private var location = ""
|
||||
@State private var date = DayMath.today()
|
||||
@State private var timeDate = Date()
|
||||
@State private var title = ""
|
||||
@@ -43,7 +44,7 @@ struct SpecialServiceSheet: View {
|
||||
VStack(alignment: .leading, spacing: 22) {
|
||||
FormSection(title: "Ort & Zeit") {
|
||||
HStack(spacing: 12) {
|
||||
LabeledField(label: "Kirche") {
|
||||
LabeledField(label: "Kirche / Zuordnung") {
|
||||
Picker("", selection: $churchID) {
|
||||
ForEach(model.churches) { church in
|
||||
Text(church.name).tag(church.id)
|
||||
@@ -63,6 +64,13 @@ struct SpecialServiceSheet: View {
|
||||
.datePickerStyle(.field)
|
||||
}
|
||||
}
|
||||
LabeledField(label: "Ort (Freitext)") {
|
||||
TextField("z. B. Open-Air auf dem Theaterplatz", text: $location)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
}
|
||||
Text("Leer lassen, wenn der Gottesdienst in der gewählten Kirche stattfindet. Der Freitext hat Vorrang vor dem Kirchnamen.")
|
||||
.font(.system(size: 9))
|
||||
.foregroundStyle(LP.inkTertiary)
|
||||
}
|
||||
|
||||
if let day = liturgicalDay {
|
||||
@@ -154,6 +162,7 @@ struct SpecialServiceSheet: View {
|
||||
existing = request.service
|
||||
if let service = existing {
|
||||
churchID = service.churchID
|
||||
location = service.location ?? ""
|
||||
date = service.date
|
||||
timeDate = calendarTime(minutes: service.timeMinutes)
|
||||
title = service.title
|
||||
@@ -163,6 +172,7 @@ struct SpecialServiceSheet: View {
|
||||
return
|
||||
}
|
||||
churchID = request.churchID ?? model.churches.first?.id ?? ""
|
||||
location = ""
|
||||
date = request.date
|
||||
timeDate = calendarTime(minutes: 18 * 60)
|
||||
if let day = liturgicalDay {
|
||||
@@ -181,6 +191,7 @@ struct SpecialServiceSheet: View {
|
||||
let service = ServiceOccurrence(
|
||||
id: existing?.id ?? UUID().uuidString,
|
||||
churchID: churchID,
|
||||
location: location,
|
||||
templateID: nil,
|
||||
date: date,
|
||||
timeMinutes: minutes,
|
||||
|
||||
@@ -10,7 +10,11 @@ public final class AppDatabase {
|
||||
self.path = path
|
||||
self.database = try SQLiteDatabase(path: path)
|
||||
try migrate()
|
||||
if seedDemo, try churchCount() == 0 {
|
||||
// Only seed on a genuinely fresh install. After the user explicitly
|
||||
// deletes all data we persist a marker so demo data does not reappear.
|
||||
if seedDemo,
|
||||
try churchCount() == 0,
|
||||
setting("suppressDemoSeed") != "1" {
|
||||
try DemoData.seed(into: self)
|
||||
}
|
||||
}
|
||||
@@ -91,6 +95,7 @@ public final class AppDatabase {
|
||||
CREATE TABLE IF NOT EXISTS services (
|
||||
id TEXT PRIMARY KEY,
|
||||
church_id TEXT NOT NULL REFERENCES churches(id) ON DELETE CASCADE,
|
||||
location TEXT NOT NULL DEFAULT '',
|
||||
template_id TEXT REFERENCES service_templates(id) ON DELETE SET NULL,
|
||||
date TEXT NOT NULL,
|
||||
time_minutes INTEGER NOT NULL,
|
||||
@@ -142,7 +147,19 @@ public final class AppDatabase {
|
||||
);
|
||||
"""
|
||||
try database.execute(schema)
|
||||
try database.run("INSERT OR IGNORE INTO settings(key, value) VALUES('schemaVersion', '1')")
|
||||
// Older databases predate the free-text location for special services.
|
||||
try addColumnIfMissing(
|
||||
table: "services",
|
||||
column: "location",
|
||||
definition: "TEXT NOT NULL DEFAULT ''"
|
||||
)
|
||||
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('schemaVersion', '2')")
|
||||
}
|
||||
|
||||
private func addColumnIfMissing(table: String, column: String, definition: String) throws {
|
||||
let columns = try database.query("PRAGMA table_info(\(table))")
|
||||
guard !columns.contains(where: { $0.string("name") == column }) else { return }
|
||||
try database.execute("ALTER TABLE \(table) ADD COLUMN \(column) \(definition);")
|
||||
}
|
||||
|
||||
// MARK: - Churches
|
||||
@@ -375,15 +392,17 @@ public final class AppDatabase {
|
||||
|
||||
public func upsert(_ service: ServiceOccurrence) throws {
|
||||
try database.run("""
|
||||
INSERT INTO services(id, church_id, template_id, date, time_minutes, title, lectors_needed,
|
||||
INSERT INTO services(id, church_id, location, template_id, date, time_minutes, title, lectors_needed,
|
||||
helpers_needed, kind, notes, locked, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET church_id=excluded.church_id, template_id=excluded.template_id,
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET church_id=excluded.church_id, location=excluded.location,
|
||||
template_id=excluded.template_id,
|
||||
date=excluded.date, time_minutes=excluded.time_minutes, title=excluded.title,
|
||||
lectors_needed=excluded.lectors_needed, helpers_needed=excluded.helpers_needed,
|
||||
kind=excluded.kind, notes=excluded.notes, locked=excluded.locked
|
||||
""", [
|
||||
.text(service.id), .text(service.churchID), service.templateID.map(SQLiteValue.text) ?? .null,
|
||||
.text(service.id), .text(service.churchID), .text(service.location ?? ""),
|
||||
service.templateID.map(SQLiteValue.text) ?? .null,
|
||||
.dateKey(service.date), .int(service.timeMinutes), .text(service.title),
|
||||
.int(service.lectorsNeeded), .int(service.helpersNeeded), .text(service.kind.rawValue),
|
||||
.text(service.notes), .bool(service.locked), .text(ISO8601DateFormatter().string(from: service.createdAt))
|
||||
@@ -401,6 +420,7 @@ public final class AppDatabase {
|
||||
return ServiceOccurrence(
|
||||
id: id,
|
||||
churchID: churchID,
|
||||
location: row.string("location", default: ""),
|
||||
templateID: row.string("template_id"),
|
||||
date: date,
|
||||
timeMinutes: row.int("time_minutes", default: 600),
|
||||
@@ -739,12 +759,25 @@ public final class AppDatabase {
|
||||
return value
|
||||
}
|
||||
|
||||
/// Removes all content while keeping application settings (range, preferences).
|
||||
/// By default a marker is stored so the demo dataset is not re-seeded on the
|
||||
/// next launch; resetting the demo clears that marker again.
|
||||
public func deleteAllData(markDemoSuppressed: Bool = true) throws {
|
||||
try database.transaction {
|
||||
try database.execute("""
|
||||
DELETE FROM assignments; DELETE FROM services; DELETE FROM service_exceptions;
|
||||
DELETE FROM service_templates; DELETE FROM absences; DELETE FROM people;
|
||||
DELETE FROM churches; DELETE FROM liturgical_days;
|
||||
""")
|
||||
if markDemoSuppressed {
|
||||
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('suppressDemoSeed', '1')")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func resetDemoData() throws {
|
||||
try database.execute("""
|
||||
DELETE FROM assignments; DELETE FROM services; DELETE FROM service_exceptions;
|
||||
DELETE FROM service_templates; DELETE FROM absences; DELETE FROM people;
|
||||
DELETE FROM churches; DELETE FROM liturgical_days;
|
||||
""")
|
||||
try deleteAllData(markDemoSuppressed: false)
|
||||
try database.run("DELETE FROM settings WHERE key='suppressDemoSeed'")
|
||||
try DemoData.seed(into: self)
|
||||
}
|
||||
|
||||
|
||||
@@ -284,6 +284,11 @@ public enum DemoData {
|
||||
ServiceOccurrence(churchID: Church.andreasID, date: date("2026-11-30"), timeMinutes: DayMath.minutes(hour: 18, minute: 0),
|
||||
title: "Patronatsfest St. Andreas", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
|
||||
notes: "Hochfest des heiligen Andreas"),
|
||||
ServiceOccurrence(churchID: Church.herzJesuID, location: "Open-Air auf dem Theaterplatz",
|
||||
date: date("2026-06-04"), timeMinutes: DayMath.minutes(hour: 10, minute: 0),
|
||||
title: "Fronleichnamsmesse",
|
||||
lectorsNeeded: 1, helpersNeeded: 2, kind: .special,
|
||||
notes: "Gemeinsame Messfeier der Pfarreiengemeinschaft im Freien"),
|
||||
ServiceOccurrence(churchID: Church.andreasID, date: date("2026-12-24"), timeMinutes: DayMath.minutes(hour: 16, minute: 0),
|
||||
title: "Familienchristmette", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
|
||||
notes: "Kinder- und Familienchristmette"),
|
||||
|
||||
@@ -114,7 +114,7 @@ public struct LiturgicalCalendarAPI: Sendable {
|
||||
|
||||
var request = URLRequest(url: url)
|
||||
request.timeoutInterval = 45
|
||||
request.setValue("LektorenPlan/0.1 (macOS; Pfarrei Bad Godesberg)", forHTTPHeaderField: "User-Agent")
|
||||
request.setValue("LektorenPlan/0.9 (macOS; Pfarrei Bad Godesberg)", forHTTPHeaderField: "User-Agent")
|
||||
request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
|
||||
|
||||
let (data, response) = try await URLSession.shared.data(for: request)
|
||||
|
||||
@@ -35,6 +35,15 @@ public enum Role: String, Codable, CaseIterable, Identifiable, Sendable, Hashabl
|
||||
case .helper: "hand.raised.fill"
|
||||
}
|
||||
}
|
||||
|
||||
/// The other role a service may need. Lector and communion helper do not
|
||||
/// exclude each other, so one person can fill both at the same service.
|
||||
public var complementary: Role {
|
||||
switch self {
|
||||
case .lector: .helper
|
||||
case .helper: .lector
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Church
|
||||
@@ -155,6 +164,12 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
|
||||
return "\(firstName) \(initial)."
|
||||
}
|
||||
|
||||
/// Compact display for the calendar: surname in full, first name abbreviated.
|
||||
public var abbreviatedName: String {
|
||||
guard let initial = firstName.first else { return lastName }
|
||||
return "\(initial). \(lastName)"
|
||||
}
|
||||
|
||||
public var roleLabel: String {
|
||||
let ordered = Role.allCases.filter { roles.contains($0) }
|
||||
return ordered.map(\.title).joined(separator: " · ")
|
||||
@@ -292,6 +307,9 @@ public enum ServiceKind: String, Codable, CaseIterable, Sendable {
|
||||
public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
|
||||
public var id: String
|
||||
public var churchID: String
|
||||
/// Free-text location for special services (e.g. open-air worship).
|
||||
/// `nil` means the service takes place in the assigned church.
|
||||
public var location: String?
|
||||
public var templateID: String?
|
||||
public var date: Date
|
||||
public var timeMinutes: Int
|
||||
@@ -306,6 +324,7 @@ public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
|
||||
public init(
|
||||
id: String = UUID().uuidString,
|
||||
churchID: String,
|
||||
location: String? = nil,
|
||||
templateID: String? = nil,
|
||||
date: Date,
|
||||
timeMinutes: Int,
|
||||
@@ -319,6 +338,8 @@ public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
|
||||
) {
|
||||
self.id = id
|
||||
self.churchID = churchID
|
||||
let trimmedLocation = location?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
self.location = (trimmedLocation?.isEmpty ?? true) ? nil : trimmedLocation
|
||||
self.templateID = templateID
|
||||
self.date = DayMath.normalize(date)
|
||||
self.timeMinutes = timeMinutes
|
||||
@@ -331,6 +352,10 @@ public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
|
||||
self.createdAt = createdAt
|
||||
}
|
||||
|
||||
public func placeName(church: Church) -> String {
|
||||
location ?? church.name
|
||||
}
|
||||
|
||||
public var timeLabel: String { DayMath.timeString(minutes: timeMinutes) }
|
||||
public var dateKey: String { DayMath.key(date) }
|
||||
public var requiredSlots: Int { lectorsNeeded + helpersNeeded }
|
||||
@@ -877,6 +902,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
|
||||
public var weightChurchPreference: Double
|
||||
public var weightServicePreference: Double
|
||||
public var weightFairness: Double
|
||||
public var weightDualRolePreference: Double
|
||||
public var maxAssignmentsPerDay: Int
|
||||
|
||||
public init(
|
||||
@@ -886,6 +912,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
|
||||
weightChurchPreference: Double = 8,
|
||||
weightServicePreference: Double = 4,
|
||||
weightFairness: Double = 2.2,
|
||||
weightDualRolePreference: Double = 14,
|
||||
maxAssignmentsPerDay: Int = 1
|
||||
) {
|
||||
self.replaceExisting = replaceExisting
|
||||
@@ -894,6 +921,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
|
||||
self.weightChurchPreference = weightChurchPreference
|
||||
self.weightServicePreference = weightServicePreference
|
||||
self.weightFairness = weightFairness
|
||||
self.weightDualRolePreference = weightDualRolePreference
|
||||
self.maxAssignmentsPerDay = maxAssignmentsPerDay
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,9 @@ public struct ServicePlanner {
|
||||
|
||||
var totalByPerson: [String: Int] = [:]
|
||||
var monthByPerson: [String: Int] = [:]
|
||||
var dayByPerson: [String: Int] = [:]
|
||||
// Count distinct services per day. Both roles at the same service do not
|
||||
// count as a double booking, so one person can be lector and helper there.
|
||||
var dayServicesByPerson: [String: Set<String>] = [:]
|
||||
var churchByPerson: [String: [String: Int]] = [:]
|
||||
var lastDateByPerson: [String: Date] = [:]
|
||||
|
||||
@@ -48,7 +50,7 @@ public struct ServicePlanner {
|
||||
let month = DayMath.monthKey(service.date)
|
||||
totalByPerson[assignment.personID, default: 0] += 1
|
||||
monthByPerson["\(assignment.personID)|\(month)", default: 0] += 1
|
||||
dayByPerson["\(assignment.personID)|\(service.dateKey)", default: 0] += 1
|
||||
dayServicesByPerson["\(assignment.personID)|\(service.dateKey)", default: []].insert(service.id)
|
||||
churchByPerson[assignment.personID, default: [:]][service.churchID, default: 0] += 1
|
||||
let previous = lastDateByPerson[assignment.personID]
|
||||
if previous == nil || service.date > previous! {
|
||||
@@ -66,6 +68,13 @@ public struct ServicePlanner {
|
||||
var newAssignments: [Assignment] = []
|
||||
|
||||
for service in sortedServices {
|
||||
// Roles already covered at this service. A person may appear in both
|
||||
// roles, but not twice in the same role.
|
||||
var assignedRolesByPerson: [String: Set<Role>] = [:]
|
||||
for assignment in working where assignment.serviceID == service.id {
|
||||
assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role)
|
||||
}
|
||||
|
||||
for role in Role.allCases {
|
||||
let required = service.requiredCount(for: role)
|
||||
guard required > 0 else { continue }
|
||||
@@ -73,7 +82,6 @@ public struct ServicePlanner {
|
||||
if existingForRole >= required { continue }
|
||||
|
||||
for _ in existingForRole..<required {
|
||||
let alreadyAssigned = Set(working.filter { $0.serviceID == service.id }.map(\.personID))
|
||||
let result = bestCandidate(
|
||||
for: service,
|
||||
role: role,
|
||||
@@ -82,10 +90,10 @@ public struct ServicePlanner {
|
||||
absencesByPerson: absencesByPerson,
|
||||
totalByPerson: totalByPerson,
|
||||
monthByPerson: monthByPerson,
|
||||
dayByPerson: dayByPerson,
|
||||
dayServicesByPerson: dayServicesByPerson,
|
||||
churchByPerson: churchByPerson,
|
||||
lastDateByPerson: lastDateByPerson,
|
||||
alreadyAssigned: alreadyAssigned
|
||||
assignedRolesByPerson: assignedRolesByPerson
|
||||
)
|
||||
switch result {
|
||||
case .success(let person):
|
||||
@@ -98,9 +106,10 @@ public struct ServicePlanner {
|
||||
working.append(assignment)
|
||||
totalByPerson[person.id, default: 0] += 1
|
||||
monthByPerson["\(person.id)|\(DayMath.monthKey(service.date))", default: 0] += 1
|
||||
dayByPerson["\(person.id)|\(service.dateKey)", default: 0] += 1
|
||||
dayServicesByPerson["\(person.id)|\(service.dateKey)", default: []].insert(service.id)
|
||||
churchByPerson[person.id, default: [:]][service.churchID, default: 0] += 1
|
||||
lastDateByPerson[person.id] = service.date
|
||||
assignedRolesByPerson[person.id, default: []].insert(role)
|
||||
case .failure(let reason):
|
||||
unfilled.append(UnfilledSlot(
|
||||
service: service,
|
||||
@@ -144,17 +153,18 @@ public struct ServicePlanner {
|
||||
absencesByPerson: [String: [Absence]],
|
||||
totalByPerson: [String: Int],
|
||||
monthByPerson: [String: Int],
|
||||
dayByPerson: [String: Int],
|
||||
dayServicesByPerson: [String: Set<String>],
|
||||
churchByPerson: [String: [String: Int]],
|
||||
lastDateByPerson: [String: Date],
|
||||
alreadyAssigned: Set<String>
|
||||
assignedRolesByPerson: [String: Set<Role>]
|
||||
) -> CandidateResult {
|
||||
var candidates: [(Person, Double)] = []
|
||||
var blockedReasons: [String: Int] = [:]
|
||||
var eligiblePeople: [Person] = []
|
||||
|
||||
for person in people where person.canFill(role) {
|
||||
guard !alreadyAssigned.contains(person.id) else {
|
||||
blockedReasons["bereits im Gottesdienst", default: 0] += 1
|
||||
let assignedRoles = assignedRolesByPerson[person.id] ?? []
|
||||
guard !assignedRoles.contains(role) else {
|
||||
blockedReasons["bereits für diesen Dienst eingeteilt", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
if let absences = absencesByPerson[person.id], absences.contains(where: { $0.overlaps(service.date) }) {
|
||||
@@ -173,13 +183,41 @@ public struct ServicePlanner {
|
||||
blockedReasons["Monatslimit erreicht", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
let usedThisDay = dayByPerson["\(person.id)|\(service.dateKey)", default: 0]
|
||||
if usedThisDay >= options.maxAssignmentsPerDay {
|
||||
let usedServicesThisDay = dayServicesByPerson["\(person.id)|\(service.dateKey)", default: []]
|
||||
// A second role at the very same service is not a double booking.
|
||||
if usedServicesThisDay.count >= options.maxAssignmentsPerDay,
|
||||
!usedServicesThisDay.isSubset(of: [service.id]) {
|
||||
blockedReasons["bereits an diesem Tag", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
|
||||
eligiblePeople.append(person)
|
||||
}
|
||||
|
||||
// The dual-role preference is a tie-breaker, not a way to concentrate
|
||||
// assignments on one person. If another suitable person has noticeably
|
||||
// fewer assignments, fairness takes priority over giving both roles to
|
||||
// the same person.
|
||||
let minimumTotal = eligiblePeople.map { totalByPerson[$0.id, default: 0] }.min() ?? 0
|
||||
let fairnessSlack = 1
|
||||
|
||||
var candidates: [(Person, Double)] = []
|
||||
for person in eligiblePeople {
|
||||
let assignedRoles = assignedRolesByPerson[person.id] ?? []
|
||||
let total = totalByPerson[person.id, default: 0]
|
||||
let withinFairnessReach = total - minimumTotal <= fairnessSlack
|
||||
|
||||
var score = 10.0
|
||||
if withinFairnessReach, assignedRoles.contains(role.complementary) {
|
||||
// The same person already covers the other role here — prefer
|
||||
// keeping both duties with them while the distribution stays fair.
|
||||
score += options.weightDualRolePreference
|
||||
} else if withinFairnessReach,
|
||||
service.rolesNeeded.count > 1,
|
||||
person.roles.contains(where: { $0 != role && service.requiredCount(for: $0) > 0 }) {
|
||||
// On services needing both roles, favour people who can cover both.
|
||||
score += options.weightDualRolePreference
|
||||
}
|
||||
if person.preferredChurchIDs.contains(service.churchID) {
|
||||
score += options.weightChurchPreference
|
||||
}
|
||||
@@ -197,7 +235,6 @@ public struct ServicePlanner {
|
||||
if person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
|
||||
score += 3
|
||||
}
|
||||
let total = totalByPerson[person.id, default: 0]
|
||||
score -= Double(total) * options.weightFairness
|
||||
let churchCount = churchByPerson[person.id]?[service.churchID, default: 0] ?? 0
|
||||
score -= Double(churchCount) * 0.4
|
||||
|
||||
@@ -28,6 +28,73 @@ final class CoreTests: XCTestCase {
|
||||
XCTAssertTrue(person.roles.contains(.lector))
|
||||
}
|
||||
|
||||
func testDemoResetRecreatesData() throws {
|
||||
let db = try AppDatabase.makeInMemory(seedDemo: true)
|
||||
let serviceCount = try db.serviceCount()
|
||||
XCTAssertEqual(try db.churches().count, 4)
|
||||
XCTAssertGreaterThan(serviceCount, 0)
|
||||
|
||||
try db.deleteAllData()
|
||||
XCTAssertEqual(try db.churches().count, 0)
|
||||
XCTAssertEqual(try db.people().count, 0)
|
||||
XCTAssertEqual(try db.serviceCount(), 0)
|
||||
XCTAssertEqual(try db.assignmentCount(), 0)
|
||||
|
||||
try db.resetDemoData()
|
||||
|
||||
XCTAssertEqual(try db.churches().count, 4)
|
||||
XCTAssertEqual(try db.people().count, 22)
|
||||
XCTAssertEqual(try db.serviceCount(), serviceCount)
|
||||
XCTAssertGreaterThan(try db.assignments(in: DayRange.year(2025)).count, 0)
|
||||
}
|
||||
|
||||
func testDeleteAllDataDoesNotReseedOnReopen() throws {
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("lp-\(UUID().uuidString).sqlite")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
do {
|
||||
let db = try AppDatabase(path: url.path, seedDemo: true)
|
||||
XCTAssertEqual(try db.churches().count, 4)
|
||||
try db.deleteAllData()
|
||||
XCTAssertEqual(try db.churches().count, 0)
|
||||
XCTAssertEqual(db.setting("suppressDemoSeed"), "1")
|
||||
}
|
||||
|
||||
// Reopening must not silently restore the demo dataset.
|
||||
let reopened = try AppDatabase(path: url.path, seedDemo: true)
|
||||
XCTAssertEqual(try reopened.churches().count, 0)
|
||||
|
||||
// Explicitly restoring the demo clears the marker.
|
||||
try reopened.resetDemoData()
|
||||
XCTAssertEqual(try reopened.churches().count, 4)
|
||||
XCTAssertNil(reopened.setting("suppressDemoSeed"))
|
||||
}
|
||||
|
||||
func testSpecialServiceLocationRoundTrip() throws {
|
||||
let db = try AppDatabase.makeInMemory(seedDemo: true)
|
||||
let date = DayMath.date(fromKey: "2026-07-12")!
|
||||
let service = ServiceOccurrence(
|
||||
churchID: Church.andreasID,
|
||||
location: "Open-Air auf dem Theaterplatz",
|
||||
date: date,
|
||||
timeMinutes: 18 * 60,
|
||||
title: "Open-Air-Messe",
|
||||
kind: .special
|
||||
)
|
||||
try db.upsert(service)
|
||||
|
||||
let loaded = try XCTUnwrap(try db.service(id: service.id))
|
||||
XCTAssertEqual(loaded.location, "Open-Air auf dem Theaterplatz")
|
||||
let church = try XCTUnwrap(try db.churches().first { $0.id == Church.andreasID })
|
||||
XCTAssertEqual(loaded.placeName(church: church), "Open-Air auf dem Theaterplatz")
|
||||
|
||||
var cleared = loaded
|
||||
cleared.location = " "
|
||||
try db.upsert(cleared)
|
||||
XCTAssertNil(try db.service(id: service.id)?.location)
|
||||
}
|
||||
|
||||
func testPlannerRespectsAbsenceAndFillsSlots() throws {
|
||||
let db = try AppDatabase.makeInMemory(seedDemo: false)
|
||||
let church = Church(id: "c1", name: "Testkirche", shortName: "Test", symbol: .chapel, colorHex: "#000000")
|
||||
@@ -51,6 +118,130 @@ final class CoreTests: XCTestCase {
|
||||
XCTAssertEqual(result.assignments.first?.personID, "b")
|
||||
}
|
||||
|
||||
func testPlannerAssignsSamePersonToBothComplementaryRoles() {
|
||||
let date = DayMath.date(fromKey: "2026-11-08")! // Sunday
|
||||
let dual = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10)
|
||||
let lectorOnly = Person(
|
||||
id: "lector", firstName: "Lea", lastName: "Lektor", roles: [.lector],
|
||||
preferredChurchIDs: ["c1"], maxPerMonth: 10
|
||||
)
|
||||
let helperOnly = Person(
|
||||
id: "helper", firstName: "Hanna", lastName: "Helfer", roles: [.helper],
|
||||
preferredChurchIDs: ["c1"], maxPerMonth: 10
|
||||
)
|
||||
let service = ServiceOccurrence(
|
||||
churchID: "c1",
|
||||
date: date,
|
||||
timeMinutes: 600,
|
||||
title: "Messe",
|
||||
lectorsNeeded: 1,
|
||||
helpersNeeded: 1
|
||||
)
|
||||
let planner = ServicePlanner(
|
||||
people: [dual, lectorOnly, helperOnly],
|
||||
absences: [],
|
||||
services: [service]
|
||||
)
|
||||
|
||||
let result = planner.plan()
|
||||
XCTAssertEqual(result.filledCount, 2)
|
||||
XCTAssertEqual(result.assignments.filter { $0.personID == "dual" }.count, 2)
|
||||
XCTAssertEqual(Set(result.assignments.filter { $0.personID == "dual" }.map(\.role)), Set(Role.allCases))
|
||||
XCTAssertEqual(result.assignments.count, 2)
|
||||
}
|
||||
|
||||
func testPlannerFairnessOverridesDualRolePreference() {
|
||||
let start = DayMath.date(fromKey: "2026-11-01")!
|
||||
let dual = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10)
|
||||
let lectorOnly = Person(id: "lector", firstName: "Lea", lastName: "Lektor", roles: [.lector], maxPerMonth: 10)
|
||||
let helperOnly = Person(id: "helper", firstName: "Hanna", lastName: "Helfer", roles: [.helper], maxPerMonth: 10)
|
||||
|
||||
// The dual-role person already has many assignments; the others have none.
|
||||
var services: [ServiceOccurrence] = []
|
||||
var existing: [Assignment] = []
|
||||
for index in 0..<5 {
|
||||
let service = ServiceOccurrence(
|
||||
id: "history-\(index)",
|
||||
churchID: "c1",
|
||||
date: DayMath.adding(days: index, to: start),
|
||||
timeMinutes: 600,
|
||||
title: "Messe",
|
||||
lectorsNeeded: 0,
|
||||
helpersNeeded: 0
|
||||
)
|
||||
services.append(service)
|
||||
existing.append(Assignment(id: "history-a-\(index)", serviceID: service.id, personID: "dual", role: .lector))
|
||||
}
|
||||
|
||||
let target = ServiceOccurrence(
|
||||
id: "target",
|
||||
churchID: "c1",
|
||||
date: DayMath.adding(days: 10, to: start),
|
||||
timeMinutes: 600,
|
||||
title: "Messe",
|
||||
lectorsNeeded: 1,
|
||||
helpersNeeded: 1
|
||||
)
|
||||
services.append(target)
|
||||
|
||||
let planner = ServicePlanner(
|
||||
people: [dual, lectorOnly, helperOnly],
|
||||
absences: [],
|
||||
services: services,
|
||||
existingAssignments: existing
|
||||
)
|
||||
|
||||
let result = planner.plan()
|
||||
let targetAssignments = result.assignments.filter { $0.serviceID == target.id }
|
||||
XCTAssertEqual(targetAssignments.count, 2)
|
||||
XCTAssertEqual(Set(targetAssignments.map(\.personID)), Set(["lector", "helper"]))
|
||||
XCTAssertFalse(targetAssignments.contains { $0.personID == "dual" })
|
||||
}
|
||||
|
||||
func testPlannerStillRejectsDuplicateRoleForSamePerson() {
|
||||
let date = DayMath.date(fromKey: "2026-11-08")!
|
||||
let dual = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10)
|
||||
let service = ServiceOccurrence(
|
||||
churchID: "c1",
|
||||
date: date,
|
||||
timeMinutes: 600,
|
||||
title: "Messe",
|
||||
lectorsNeeded: 2,
|
||||
helpersNeeded: 0
|
||||
)
|
||||
let planner = ServicePlanner(people: [dual], absences: [], services: [service])
|
||||
|
||||
let result = planner.plan()
|
||||
XCTAssertEqual(result.filledCount, 1)
|
||||
XCTAssertEqual(result.assignments.count, 1)
|
||||
XCTAssertEqual(result.unfilled.count, 1)
|
||||
}
|
||||
|
||||
func testDatabaseAllowsSamePersonInBothRoles() throws {
|
||||
let db = try AppDatabase.makeInMemory(seedDemo: false)
|
||||
let church = Church(id: "c1", name: "Testkirche", shortName: "Test", symbol: .chapel, colorHex: "#000000")
|
||||
try db.upsert(church)
|
||||
let person = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10)
|
||||
try db.upsert(person)
|
||||
let date = DayMath.date(fromKey: "2026-11-08")!
|
||||
let service = ServiceOccurrence(
|
||||
churchID: "c1",
|
||||
date: date,
|
||||
timeMinutes: 600,
|
||||
title: "Messe",
|
||||
lectorsNeeded: 1,
|
||||
helpersNeeded: 1
|
||||
)
|
||||
try db.upsert(service)
|
||||
|
||||
try db.setAssignment(serviceID: service.id, role: .lector, personID: person.id)
|
||||
try db.setAssignment(serviceID: service.id, role: .helper, personID: person.id)
|
||||
|
||||
let assignments = try db.assignments(serviceIDs: [service.id])
|
||||
XCTAssertEqual(assignments.filter { $0.personID == person.id }.count, 2)
|
||||
XCTAssertEqual(Set(assignments.filter { $0.personID == person.id }.map(\.role)), Set(Role.allCases))
|
||||
}
|
||||
|
||||
func testExchangeRoundTrip() throws {
|
||||
let source = try AppDatabase.makeInMemory(seedDemo: true)
|
||||
let range = DayRange.quarter(containing: DayMath.date(fromKey: "2026-11-07")!)
|
||||
@@ -101,6 +292,11 @@ final class CoreTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testAbbreviatedNameKeepsFullSurname() {
|
||||
let person = Person(firstName: "Anna", lastName: "Berg")
|
||||
XCTAssertEqual(person.abbreviatedName, "A. Berg")
|
||||
}
|
||||
|
||||
func testRangeLabelsAndPreferenceRate() {
|
||||
let range = DayRange(
|
||||
start: DayMath.date(fromKey: "2026-10-01")!,
|
||||
|
||||
+12
@@ -23,3 +23,15 @@ Die Visualisierung soll grafisch eingängig sein. So sollten beispielsweise Kirc
|
||||
Ebenso können durch eindeutige Symbole bestimmte Hochfeste hervorgehoben werden.
|
||||
|
||||
Erstelle ein Grobkonzept und einen ersten Prototypen.
|
||||
|
||||
------8<-------------
|
||||
|
||||
1) Das Löschen der Demodaten funktioniert noch nicht.
|
||||
2) Ich benötige bei dem Erstellen des PDS und dem Ausdruck weitere Optionen:
|
||||
Es soll eine altenative reduzierte PDF/Ausdruck-Variante geben, die auf A4 im Hochformat in einer Listenansicht nur die Tage mit Messen auflistet.
|
||||
Eine Zeile enthält einen Gottesdienst mit Kirche und Uhrzeit, in derselben Zeile sollen in jeweils eigenen Spalten Lektoren und Kommunionhelfer mit Nachnamen genannt werden.
|
||||
Links neben den passenden Zeilen wird das Datum des Tages verkürzzt dargestellt, nur Hinweise auf Hochfeste oder Sondergottesdienste sollen erwähnt werden.
|
||||
3) Bei Sondergottesdiensten muss als Kirche/Ort ein Freitext möglich gemacht werden, damit zum Beispiel Open-Air-Gottesdienste oder Sonderorte benannt werden können.
|
||||
|
||||
------8<-------------
|
||||
|
||||
Reference in new issue
Block a user