1. Prototyp

This commit is contained in:
concierge committed 2026-11-07 11:32:18 +01:00
1 parent e723eee440
commit c24bc91768
37 files changed
+11610

No files matched your search

+292
View File
@@ -0,0 +1,292 @@
# LektorenPlan – Grobkonzept
**Pfarreiengemeinschaft Bad Godesberg · Erzbistum Köln**
Planung von Lektorinnen, Lektoren und Kommunionhelferinnen/-helfern für
St. Andreas, St. Evergislus, Herz Jesu und St. Hildegard.
---
## 1. Zielbild
LektorenPlan unterstützt das Pfarrbüro und das ehrenamtliche Planungsteam dabei,
Gottesdienste über einen frei wählbaren Zeitraum mit den passenden Diensten zu
besetzen. Die Anwendung verbindet drei Perspektiven:
1. **Kalender** – jeder Tag des Zeitraums mit Liturgie, Lesungen und allen
Gottesdiensten der vier Kirchen.
2. **Planung** – automatische Verteilung unter harten Randbedingungen und
weichen Präferenzen, mit manueller Nachsteuerung.
3. **Auswertung** – Einsatzhäufigkeit, Verteilung auf Orte, Fairness und
Präferenztreffer für beliebige vergangene oder künftige Zeitfenster.
Die Planung ist lokal, offline nutzbar und speichert alle Daten in einer
SQLite-Datenbank. Liturgische Daten werden bevorzugt aus dem mitgelieferten
Bestand gelesen und können online aktualisiert werden.
---
## 2. Nutzer und typische Abläufe
| Rolle | Aufgabe |
|---|---|
| Planungsteam | Zeitraum wählen, Dienste erzeugen, automatisch planen, Lücken manuell schließen, Ergebnis drucken |
| Ressourcenverwaltung | Personen, Rollen, Präferenzen, Abwesenheiten und Monatslimits pflegen |
| Gottesdienstordnung | Wiederkehrende Termine, Ausnahmen und Sondergottesdienste pflegen |
| Austausch | Planungsabschnitte oder Stammdaten als JSON zwischen Installationen übergeben |
Typischer Ablauf eines Quartals:
1. Zeitraum über den Zeitstrahl oder eine Zeitmarke (Quartal, Osterzeit,
Weihnachtszeit, Kirchenjahr) wählen.
2. Gottesdienste aus den Vorlagen erzeugen und Sondertermine ergänzen.
3. „Offene Dienste besetzen“ oder „Zeitraum neu planen“ ausführen.
4. Offene Dienste im Ergebnis prüfen und im Detaildialog manuell besetzen.
5. Statistik prüfen, PDF-Vorschau öffnen, drucken oder sichern.
6. Bei Bedarf Plan oder Ressourcen exportieren.
---
## 3. Architektur
```
LektorenPlan.app
├── LektorenPlan (SwiftUI, macOS 14+)
│ ├── RootView / Sidebar
│ ├── PlanningView Kalender & Tagesplanung
│ ├── ServiceOrderView Gottesdienstordnung
│ ├── TeamView Lektoren & Kommunionhelfer
│ ├── StatisticsView Auswertung (Swift Charts)
│ ├── ExchangeView Import/Export
│ ├── SettingsView Kalender, Planung, Datenhaltung
│ ├── Sheets Personen, Vorlagen, Sondertermine, Detail, PDF
│ └── PlanModel beobachtbarer App-Zustand und Aktionen
└── LektorenPlanCore
├── Models Domänenmodelle und Statistiktypen
├── DateUtils Tagesnormalisierung, Zeiträume, deutsche Formate
├── LiturgicalCalendar Osterdatum, Kirchenjahr, Hochfeste, Offline-Fallback
├── LiturgicalAPI Abruf und Parser für eucharistiefeier.de
├── SQLiteDatabase schlanker SQLite-Wrapper
├── AppDatabase Schema, CRUD, Erzeugung, Austausch, Demo-Daten
├── Planner Regel- und scorebasierte Verteilung
└── Statistics Kennzahlen und Präferenzauswertung
```
**Technische Entscheidungen**
- Swift Package Manager statt handgepflegtem Xcode-Projekt; `Package.swift`
lässt sich direkt in Xcode öffnen.
- Keine externen Abhängigkeiten. SQLite über das Systemmodul `SQLite3`.
- Core-Logik und UI sind getrennt, damit Planung und Statistik testbar bleiben.
- macOS 14 als Mindestversion, Swift-5-Sprachmodus.
- Das App-Bundle wird über `Scripts/build-app.sh` erzeugt.
---
## 4. Datenmodell
Alle Tabellen liegen in `~/Library/Application Support/LektorenPlan/lektorenplan.sqlite`.
| Tabelle | Inhalt |
|---|---|
| `churches` | Kirchen mit Kürzel, Kirchensymbol, Farbe, Adresse, Sortierung |
| `people` | Personen mit Rollen, Kontakt, Präferenzen, Monatslimit, Aktivstatus |
| `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 |
| `assignments` | Einsatz einer Person in einer Rolle, optional gesperrt |
| `liturgical_days` | Liturgischer Tag, Rang, Farbe, Lesungen, Quelle |
| `settings` | Zeitraum, Filter, Kalender- und Planungseinstellungen |
Zeiträume werden als Tagesbereich (`DayRange`) geführt. Alle Datumsangaben
werden auf 12:00 Uhr Europe/Berlin normalisiert, um Sommerzeit- und
Mitternachtsprobleme zu vermeiden. Schlüssel sind `yyyy-MM-dd`.
**Stabile IDs** (UUIDs) verbinden Datensätze beim Import. Ein Zusammenführen
aktualisiert vorhandene Kirchen, Personen und Vorlagen und ergänzt neue
Gottesdienste und Einsätze; es wird nichts gelöscht.
---
## 5. Liturgischer Kalender
- Quelle: `https://www.eucharistiefeier.de/lk/api.php` mit `kal=koeln`,
`format=json`, `info=wdtrflu`, `dup=e`, `bahn=j`.
- Für 2025–2028 liegt ein Offline-Snapshot bei (1461 Tage), damit die App
sofort und ohne Netz funktioniert.
- Beim Start wird höchstens einmal pro Tag der Jahrgang des aktuellen
Zeitraums aktualisiert. Manuelle Aktualisierung ist jederzeit möglich.
- Der lokale Rechner (`LiturgicalCalendarEngine`) bestimmt Ostern, Advent,
Kirchenjahr, Sonntage, Hochfeste und gebotene Feiertage. Er dient als
Fallback und zur Plausibilisierung.
- Angezeigt werden Tagesliturgie, Rang, liturgische Farbe, Kurzlesungen
(erste Lesung, Psalm, zweite Lesung, Evangelium) und Quellenhinweis.
**Attribution:** „Daten von www.eucharistiefeier.de“ ist in App, PDF und
Einstellungen sichtbar. Die Daten werden nur zur Anzeige genutzt; die Quelle
bleibt Eigentümerin der Daten.
---
## 6. Planungsalgorithmus
Die Planung arbeitet deterministisch und nachvollziehbar.
### Harte Ausschlüsse
Eine Person wird für einen Dienst nicht vorgeschlagen, wenn
- sie die benötigte Rolle nicht hat,
- sie im Zeitraum abwesend ist,
- sie an diesem Tag bereits eingeteilt ist,
- ihr Monatslimit erreicht ist,
- ihr bevorzugter Einsatztag nicht passt (optional, standardmäßig aktiv),
- sie bereits im selben Gottesdienst eingeplant ist.
Gesperrte Einsätze werden bei einer Neuplanung nie verändert.
### Weiche Bewertung
Jede verbleibende Person erhält einen Score:
- Grundwert,
- Bonus für bevorzugte Kirche,
- Bonus für passenden Gottesdiensttitel,
- Bonus für bevorzugten Wochentag,
- Malus für viele bisherige Einsätze (Fairness),
- Malus für viele Einsätze an derselben Kirche,
- Bonus für eine längere Pause seit dem letzten Einsatz,
- kleiner stabiler Tie-Break, damit die Verteilung reproduzierbar bleibt.
Die Gewichte sind in den Einstellungen justierbar (Fairness-Gewicht,
Einsatztage als Ausschluss). Der Planer besetzt zuerst alle Dienste des
Zeitraums und dokumentiert für offene Dienste den häufigsten Ausschlussgrund
(z. B. „Monatslimit erreicht (4 ausgeschlossen)“).
### Manuelle Nachsteuerung
Im Detaildialog eines Gottesdienstes werden Kandidaten mit Eignung, bisherigen
Einsätzen im Zeitraum, Präferenztreffer und Warnhinweisen angezeigt. Ein Klick
teilt die Person ein oder entfernt sie. Einsätze können gesperrt werden, damit
sie bei der nächsten Automatik erhalten bleiben.
---
## 7. Oberfläche und Interaktion
- **Ruhige Papieroptik** mit warmen Hintergründen, Akzentgrün, Gold und
Burgunder; Serif-Überschriften, klare Piktogramme.
- **Kalender als Tabelle:** eine Zeile pro Tag, feste Spalten für Datum,
Liturgie/Lesungen und die vier Kirchen. Sonntage, Hochfeste und gebotene
Feiertage sind farblich hinterlegt; liturgische Farbbalken markieren den Tag.
- **Kirchen-Strichzeichnungen** (Basilika, Saalkirche, Jugendstilkirche,
moderne Kirche). Der Name erscheint im Tooltip und in der Spaltenüberschrift.
- **Symbole für Hochfeste** und Rangabzeichen (GEDENKTAG, FEST, HOCHFEST,
GEBOTEN).
- **Zeitstrahl** mit zwei Griffen, Jahresrastern und Marken für Quartale,
Osterzeit, Weihnachtszeit und Kirchenjahr. Der gewählte Bereich wird sofort
auf Tabelle und Statistik angewendet.
- **Filter** „Alle Tage“, „Mit Gottesdiensten“, „Nur offene“ und
„Sonn- & Feiertage“; Suche über Person, Ort und Lesung.
- **Servicekarten** zeigen Uhrzeit, Titel, offene Plätze und die eingeteilten
Personen. Ein Klick öffnet den Detaildialog.
- **Dialoge** für Personen, Vorlagen, Sondergottesdienste, Importvorschau und
PDF-Vorschau. Alle Dialoge haben dieselbe Kopf-/Fußstruktur.
- **Statistik** mit Kennzahlen, Balken-, Linien- und Donut-Diagrammen sowie
einer Einsatzübersicht je Person.
- **Dark Mode** ist nicht Teil des Prototyps; das Farbsystem ist bewusst auf
die helle Papieroptik ausgelegt.
---
## 8. Statistik
Für den gewählten Zeitraum werden berechnet:
- Anzahl Gottesdienste, benötigter und besetzter Dienste, offene Dienste,
- Besetzungsquote,
- Einsätze pro Person (Lektor/Kommunionhelfer, Sonntage, Kirchen),
- Fairness: Durchschnitt, Minimum, Maximum und Spannweite,
- Verlauf nach Monat (auch Monate ohne Einsätze),
- Verteilung auf die Kirchen inkl. offener Dienste,
- Präferenztreffer: Nur Einsätze von Personen mit hinterlegten Präferenzen
zählen als bewertbar; die Quote ist Treffer / bewertbare Einsätze.
- Abwesenheitstage im Zeitraum.
Die Statistik nutzt denselben Datenbestand wie die Planung und aktualisiert
sich beim Wechsel des Zeitraums, bei Planungsänderungen und beim Import.
---
## 9. Import und Export
Das Austauschformat ist lesbares JSON mit:
- Format- und App-Version,
- Exportzeitpunkt und Notiz,
- Umfang (`plan` oder `resources`),
- Zeitraum,
- Kirchen, Personen, Abwesenheiten, Vorlagen, Ausnahmen,
- bei `plan` zusätzlich Gottesdienste, Einsätze und liturgische Tage.
Beim Import wird die Datei zuerst gelesen und in einer Vorschau mit Anzahl der
enthaltenen Datensätze angezeigt. Erst nach Bestätigung werden die Daten
zusammengeführt. Der Import ist idempotent über stabile IDs und löscht keine
vorhandenen Daten.
---
## 10. PDF und Druck
- 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“).
- Vorschau über PDFKit mit Aktionen „Sichern“ und „Drucken“.
- Druck über `NSPrintInfo` in Querformat, ohne zusätzliche Ränder.
---
## 11. Prototyp – Stand und Grenzen
**Umgesetzt**
- Vollständiges Domänenmodell, SQLite-Schema, CRUD und Demo-Daten.
- 22 fiktive Personen, 13 wiederkehrende Vorlagen, Sondertermine und
Ausnahmen für 2025–2028.
- Liturgischer Snapshot, Online-Aktualisierung, lokaler Fallback.
- 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.
**Bewusste Grenzen**
- Einzelplatz-Anwendung ohne Benutzerkonten und Server-Synchronisation.
- Keine automatische E-Mail-Benachrichtigung an Eingeteilte.
- Keine Kalender-Exporte (ICS) und keine iCloud-Synchronisation.
- Dark Mode, VoiceOver-Feinschliff und Lokalisierung über Deutsch hinaus sind
noch nicht ausgearbeitet.
- Die Demo-Personen und -Kontaktdaten sind fiktiv.
**Nächste Schritte**
1. Reale Stammdaten importieren und Planungsregeln mit dem Team kalibrieren.
2. Benachrichtigungen und ICS-Export ergänzen.
3. Mehrbenutzerbetrieb über einen gemeinsamen Speicherort oder Server prüfen.
4. Bedienungshilfen, Dark Mode und Tastaturnavigation ausbauen.
5. Signierung/Notarisierung und Update-Mechanismus für die Verteilung.
---
## 12. Datenschutz und Betrieb
- Alle Daten bleiben lokal auf dem Mac; keine Cloud im Prototyp.
- Exportdateien enthalten personenbezogene Daten und sollten geschützt
weitergegeben werden.
- Die liturgische Quelle wird sparsam und nur zur Aktualisierung abgefragt.
- Vor einem produktiven Einsatz sind Löschkonzept, Zugriffsrechte und
Einwilligungen der ehrenamtlich Tätigen zu klären.
+45
View File
@@ -0,0 +1,45 @@
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "LektorenPlan",
defaultLocalization: "de",
platforms: [
.macOS(.v14)
],
products: [
.executable(name: "LektorenPlan", targets: ["LektorenPlan"]),
.library(name: "LektorenPlanCore", targets: ["LektorenPlanCore"])
],
targets: [
.target(
name: "LektorenPlanCore",
path: "Sources/LektorenPlanCore",
resources: [
.process("Resources")
],
swiftSettings: [
.swiftLanguageMode(.v5)
],
linkerSettings: [
.linkedLibrary("sqlite3")
]
),
.executableTarget(
name: "LektorenPlan",
dependencies: ["LektorenPlanCore"],
path: "Sources/LektorenPlan",
swiftSettings: [
.swiftLanguageMode(.v5)
]
),
.testTarget(
name: "LektorenPlanCoreTests",
dependencies: ["LektorenPlanCore"],
path: "Tests/LektorenPlanCoreTests",
swiftSettings: [
.swiftLanguageMode(.v5)
]
)
]
)
+63
View File
@@ -0,0 +1,63 @@
#!/bin/bash
set -euo pipefail
CONFIG="${1:-debug}"
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
echo "Baue LektorenPlan ($CONFIG)…"
swift build -c "$CONFIG"
BIN_DIR="$(swift build -c "$CONFIG" --show-bin-path)"
APP="$ROOT/build/LektorenPlan.app"
CONTENTS="$APP/Contents"
MACOS="$CONTENTS/MacOS"
RESOURCES="$CONTENTS/Resources"
rm -rf "$APP"
mkdir -p "$MACOS" "$RESOURCES"
cp "$BIN_DIR/LektorenPlan" "$MACOS/LektorenPlan"
# Copy SwiftPM resource bundles so Bundle.module keeps working inside the app.
for bundle in "$BIN_DIR"/*.bundle; do
[ -e "$bundle" ] || continue
cp -R "$bundle" "$RESOURCES/"
done
cat > "$CONTENTS/Info.plist" <<'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>de</string>
<key>CFBundleExecutable</key>
<string>LektorenPlan</string>
<key>CFBundleIdentifier</key>
<string>de.badgodesberg.lektorenplan</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>LektorenPlan</string>
<key>CFBundleDisplayName</key>
<string>LektorenPlan</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.1</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSHumanReadableCopyright</key>
<string>LektorenPlan Prototyp · Pfarreiengemeinschaft Bad Godesberg</string>
</dict>
</plist>
PLIST
echo "Fertig: $APP"
@@ -0,0 +1,454 @@
import SwiftUI
import LektorenPlanCore
/// Hand-drawn, reduced line illustrations of the four church buildings.
/// The drawings deliberately avoid text; the name is revealed on hover by the caller.
struct ChurchGlyph: View {
var symbol: ChurchSymbol
var tint: Color
var lineWidth: CGFloat = 1.4
var showGround: Bool = true
var body: some View {
Canvas { context, size in
let scale = min(size.width / 120, size.height / 86)
let offset = CGPoint(
x: (size.width - 120 * scale) / 2,
y: (size.height - 86 * scale) / 2
)
let transform = CGAffineTransform(translationX: offset.x, y: offset.y)
.scaledBy(x: scale, y: scale)
func path(_ build: (inout Path) -> Void) -> Path {
var p = Path()
build(&p)
return p.applying(transform)
}
switch symbol {
case .basilica:
drawBasilica(context: &context, strokeColor: tint, fillColor: tint.opacity(0.055), path: path)
case .gothic:
drawGothic(context: &context, strokeColor: tint, fillColor: tint.opacity(0.055), path: path)
case .modern:
drawModern(context: &context, strokeColor: tint, fillColor: tint.opacity(0.055), path: path)
case .rotunda:
drawRotunda(context: &context, strokeColor: tint, fillColor: tint.opacity(0.055), path: path)
case .roundTower:
drawRoundTower(context: &context, strokeColor: tint, fillColor: tint.opacity(0.055), path: path)
case .chapel:
drawChapel(context: &context, strokeColor: tint, fillColor: tint.opacity(0.055), path: path)
}
if showGround {
let ground = path { p in
p.move(to: CGPoint(x: 8, y: 76))
p.addLine(to: CGPoint(x: 112, y: 76))
}
context.stroke(ground, with: .color(tint.opacity(0.35)), style: StrokeStyle(lineWidth: 0.8, dash: [2, 3]))
}
}
.accessibilityLabel(symbol.caption)
}
private func drawBasilica(
context: inout GraphicsContext,
strokeColor: Color,
fillColor: Color,
path: ((inout Path) -> Void) -> Path
) {
let stroke = GraphicsContext.Shading.color(strokeColor)
let fill = GraphicsContext.Shading.color(fillColor)
let nave = path { p in
p.move(to: CGPoint(x: 42, y: 42))
p.addLine(to: CGPoint(x: 60, y: 28))
p.addLine(to: CGPoint(x: 78, y: 42))
p.addLine(to: CGPoint(x: 78, y: 75))
p.addLine(to: CGPoint(x: 42, y: 75))
p.closeSubpath()
}
context.fill(nave, with: fill)
context.stroke(nave, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let roof = path { p in
p.move(to: CGPoint(x: 39, y: 43))
p.addLine(to: CGPoint(x: 60, y: 26))
p.addLine(to: CGPoint(x: 81, y: 43))
}
context.stroke(roof, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let aisleLeft = path { p in
p.move(to: CGPoint(x: 27, y: 55))
p.addLine(to: CGPoint(x: 27, y: 75))
p.addLine(to: CGPoint(x: 42, y: 75))
p.addLine(to: CGPoint(x: 42, y: 50))
p.addLine(to: CGPoint(x: 32, y: 47))
}
let aisleRight = path { p in
p.move(to: CGPoint(x: 78, y: 50))
p.addLine(to: CGPoint(x: 78, y: 75))
p.addLine(to: CGPoint(x: 93, y: 75))
p.addLine(to: CGPoint(x: 93, y: 55))
p.addLine(to: CGPoint(x: 83, y: 59))
}
context.stroke(aisleLeft, with: stroke, style: StrokeStyle(lineWidth: lineWidth * 0.85, lineJoin: .round))
context.stroke(aisleRight, with: stroke, style: StrokeStyle(lineWidth: lineWidth * 0.85, lineJoin: .round))
let tower = path { p in
p.move(to: CGPoint(x: 88, y: 26))
p.addLine(to: CGPoint(x: 99, y: 26))
p.addLine(to: CGPoint(x: 99, y: 75))
p.addLine(to: CGPoint(x: 88, y: 75))
p.closeSubpath()
}
context.fill(tower, with: fill)
context.stroke(tower, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let spire = path { p in
p.move(to: CGPoint(x: 86, y: 27))
p.addLine(to: CGPoint(x: 93.5, y: 12))
p.addLine(to: CGPoint(x: 101, y: 27))
}
context.stroke(spire, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let door = path { p in
p.move(to: CGPoint(x: 55, y: 75))
p.addLine(to: CGPoint(x: 55, y: 62))
p.addQuadCurve(to: CGPoint(x: 65, y: 62), control: CGPoint(x: 60, y: 54))
p.addLine(to: CGPoint(x: 65, y: 75))
}
context.stroke(door, with: stroke, style: StrokeStyle(lineWidth: lineWidth * 0.8))
for x in [48.0, 72.0] {
let window = path { p in
p.move(to: CGPoint(x: x, y: 68))
p.addLine(to: CGPoint(x: x, y: 58))
p.addQuadCurve(to: CGPoint(x: x + 6, y: 58), control: CGPoint(x: x + 3, y: 53))
p.addLine(to: CGPoint(x: x + 6, y: 68))
}
context.stroke(window, with: .color(strokeColor.opacity(0.65)), style: StrokeStyle(lineWidth: 0.8))
}
let cross = path { p in
p.move(to: CGPoint(x: 93.5, y: 12))
p.addLine(to: CGPoint(x: 93.5, y: 4))
p.move(to: CGPoint(x: 90.5, y: 7))
p.addLine(to: CGPoint(x: 96.5, y: 7))
}
context.stroke(cross, with: stroke, style: StrokeStyle(lineWidth: lineWidth * 0.85, lineCap: .round))
}
private func drawGothic(
context: inout GraphicsContext,
strokeColor: Color,
fillColor: Color,
path: ((inout Path) -> Void) -> Path
) {
let stroke = GraphicsContext.Shading.color(strokeColor)
let fill = GraphicsContext.Shading.color(fillColor)
let body = path { p in
p.move(to: CGPoint(x: 36, y: 75))
p.addLine(to: CGPoint(x: 36, y: 44))
p.addQuadCurve(to: CGPoint(x: 60, y: 35), control: CGPoint(x: 46, y: 37))
p.addQuadCurve(to: CGPoint(x: 84, y: 44), control: CGPoint(x: 74, y: 37))
p.addLine(to: CGPoint(x: 84, y: 75))
p.closeSubpath()
}
context.fill(body, with: fill)
context.stroke(body, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let spire = path { p in
p.move(to: CGPoint(x: 31, y: 45))
p.addLine(to: CGPoint(x: 60, y: 8))
p.addLine(to: CGPoint(x: 89, y: 45))
}
context.stroke(spire, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let tower = path { p in
p.move(to: CGPoint(x: 88, y: 29))
p.addLine(to: CGPoint(x: 101, y: 29))
p.addLine(to: CGPoint(x: 101, y: 75))
p.addLine(to: CGPoint(x: 88, y: 75))
}
context.stroke(tower, with: stroke, style: StrokeStyle(lineWidth: lineWidth * 0.9))
let towerSpire = path { p in
p.move(to: CGPoint(x: 85, y: 30))
p.addLine(to: CGPoint(x: 94.5, y: 10))
p.addLine(to: CGPoint(x: 104, y: 30))
}
context.stroke(towerSpire, with: stroke, style: StrokeStyle(lineWidth: lineWidth * 0.9, lineJoin: .round))
let door = path { p in
p.move(to: CGPoint(x: 54, y: 75))
p.addLine(to: CGPoint(x: 54, y: 57))
p.addQuadCurve(to: CGPoint(x: 66, y: 57), control: CGPoint(x: 60, y: 48))
p.addLine(to: CGPoint(x: 66, y: 75))
}
context.stroke(door, with: stroke, style: StrokeStyle(lineWidth: lineWidth * 0.85))
let rose = path { p in
p.addEllipse(in: CGRect(x: 50, y: 44, width: 20, height: 20))
}
context.stroke(rose, with: .color(strokeColor.opacity(0.8)), style: StrokeStyle(lineWidth: 0.9))
for angle in stride(from: 0.0, to: 360.0, by: 60.0) {
let rad = angle * .pi / 180
let line = path { p in
p.move(to: CGPoint(x: 60, y: 54))
p.addLine(to: CGPoint(x: 60 + cos(rad) * 9, y: 54 + sin(rad) * 9))
}
context.stroke(line, with: .color(strokeColor.opacity(0.55)), style: StrokeStyle(lineWidth: 0.6))
}
let cross = path { p in
p.move(to: CGPoint(x: 60, y: 8))
p.addLine(to: CGPoint(x: 60, y: 1))
p.move(to: CGPoint(x: 57, y: 4))
p.addLine(to: CGPoint(x: 63, y: 4))
}
context.stroke(cross, with: stroke, style: StrokeStyle(lineWidth: 0.9, lineCap: .round))
}
private func drawModern(
context: inout GraphicsContext,
strokeColor: Color,
fillColor: Color,
path: ((inout Path) -> Void) -> Path
) {
let stroke = GraphicsContext.Shading.color(strokeColor)
let fill = GraphicsContext.Shading.color(fillColor)
let body = path { p in
p.move(to: CGPoint(x: 30, y: 75))
p.addLine(to: CGPoint(x: 34, y: 43))
p.addLine(to: CGPoint(x: 63, y: 31))
p.addLine(to: CGPoint(x: 87, y: 46))
p.addLine(to: CGPoint(x: 86, y: 75))
p.closeSubpath()
}
context.fill(body, with: fill)
context.stroke(body, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let roof = path { p in
p.move(to: CGPoint(x: 28, y: 45))
p.addLine(to: CGPoint(x: 63, y: 28))
p.addLine(to: CGPoint(x: 89, y: 46))
}
context.stroke(roof, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let tower = path { p in
p.move(to: CGPoint(x: 91, y: 24))
p.addLine(to: CGPoint(x: 103, y: 24))
p.addLine(to: CGPoint(x: 103, y: 75))
p.addLine(to: CGPoint(x: 91, y: 75))
p.closeSubpath()
}
context.fill(tower, with: fill)
context.stroke(tower, with: stroke, style: StrokeStyle(lineWidth: lineWidth))
let slit = path { p in
p.move(to: CGPoint(x: 96.5, y: 34))
p.addLine(to: CGPoint(x: 96.5, y: 62))
p.move(to: CGPoint(x: 98.5, y: 34))
p.addLine(to: CGPoint(x: 98.5, y: 62))
}
context.stroke(slit, with: .color(strokeColor.opacity(0.7)), style: StrokeStyle(lineWidth: 0.7))
let cross = path { p in
p.move(to: CGPoint(x: 97, y: 24))
p.addLine(to: CGPoint(x: 97, y: 12))
p.move(to: CGPoint(x: 92, y: 17))
p.addLine(to: CGPoint(x: 102, y: 17))
}
context.stroke(cross, with: stroke, style: StrokeStyle(lineWidth: 1.0, lineCap: .round))
let glass = path { p in
p.move(to: CGPoint(x: 38, y: 72))
p.addLine(to: CGPoint(x: 38, y: 50))
p.addLine(to: CGPoint(x: 58, y: 43))
p.addLine(to: CGPoint(x: 58, y: 72))
p.closeSubpath()
}
context.stroke(glass, with: .color(strokeColor.opacity(0.65)), style: StrokeStyle(lineWidth: 0.8))
for i in 0..<3 {
let x = 40.0 + Double(i) * 6
let line = path { p in
p.move(to: CGPoint(x: x, y: 70))
p.addLine(to: CGPoint(x: x + 2.5, y: 47))
}
context.stroke(line, with: .color(strokeColor.opacity(0.35)), style: StrokeStyle(lineWidth: 0.5))
}
let entrance = path { p in
p.move(to: CGPoint(x: 66, y: 75))
p.addLine(to: CGPoint(x: 66, y: 56))
p.addLine(to: CGPoint(x: 82, y: 51))
p.addLine(to: CGPoint(x: 82, y: 75))
}
context.stroke(entrance, with: .color(strokeColor.opacity(0.65)), style: StrokeStyle(lineWidth: 0.8))
}
private func drawRotunda(
context: inout GraphicsContext,
strokeColor: Color,
fillColor: Color,
path: ((inout Path) -> Void) -> Path
) {
let stroke = GraphicsContext.Shading.color(strokeColor)
let fill = GraphicsContext.Shading.color(fillColor)
let base = path { p in
p.move(to: CGPoint(x: 28, y: 75))
p.addLine(to: CGPoint(x: 32, y: 53))
p.addQuadCurve(to: CGPoint(x: 88, y: 53), control: CGPoint(x: 60, y: 39))
p.addLine(to: CGPoint(x: 92, y: 75))
p.closeSubpath()
}
context.fill(base, with: fill)
context.stroke(base, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let dome = path { p in
p.move(to: CGPoint(x: 32, y: 53))
p.addQuadCurve(to: CGPoint(x: 88, y: 53), control: CGPoint(x: 60, y: 26))
}
context.stroke(dome, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let crown = path { p in
p.move(to: CGPoint(x: 56, y: 36))
p.addLine(to: CGPoint(x: 64, y: 36))
p.addLine(to: CGPoint(x: 64, y: 31))
p.addLine(to: CGPoint(x: 56, y: 31))
p.closeSubpath()
}
context.stroke(crown, with: .color(strokeColor.opacity(0.8)), style: StrokeStyle(lineWidth: 0.8))
let cross = path { p in
p.move(to: CGPoint(x: 60, y: 31))
p.addLine(to: CGPoint(x: 60, y: 20))
p.move(to: CGPoint(x: 55.5, y: 24))
p.addLine(to: CGPoint(x: 64.5, y: 24))
}
context.stroke(cross, with: stroke, style: StrokeStyle(lineWidth: 1.0, lineCap: .round))
for x in [38.0, 47.0, 73.0, 82.0] {
let window = path { p in
p.move(to: CGPoint(x: x, y: 70))
p.addLine(to: CGPoint(x: x, y: 58))
}
context.stroke(window, with: .color(strokeColor.opacity(0.55)), style: StrokeStyle(lineWidth: 0.8))
}
let door = path { p in
p.move(to: CGPoint(x: 55, y: 75))
p.addLine(to: CGPoint(x: 55, y: 61))
p.addQuadCurve(to: CGPoint(x: 65, y: 61), control: CGPoint(x: 60, y: 55))
p.addLine(to: CGPoint(x: 65, y: 75))
}
context.stroke(door, with: stroke, style: StrokeStyle(lineWidth: lineWidth * 0.85))
}
private func drawRoundTower(
context: inout GraphicsContext,
strokeColor: Color,
fillColor: Color,
path: ((inout Path) -> Void) -> Path
) {
let stroke = GraphicsContext.Shading.color(strokeColor)
let fill = GraphicsContext.Shading.color(fillColor)
let body = path { p in
p.move(to: CGPoint(x: 35, y: 75))
p.addLine(to: CGPoint(x: 35, y: 35))
p.addLine(to: CGPoint(x: 78, y: 35))
p.addLine(to: CGPoint(x: 78, y: 75))
}
context.stroke(body, with: stroke, style: StrokeStyle(lineWidth: lineWidth))
let roof = path { p in
p.move(to: CGPoint(x: 30, y: 36))
p.addLine(to: CGPoint(x: 56.5, y: 12))
p.addLine(to: CGPoint(x: 83, y: 36))
}
context.stroke(roof, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let tower = path { p in
p.addEllipse(in: CGRect(x: 84, y: 35, width: 20, height: 40))
}
context.fill(tower, with: fill)
context.stroke(tower, with: stroke, style: StrokeStyle(lineWidth: lineWidth))
let cap = path { p in
p.move(to: CGPoint(x: 82, y: 35))
p.addQuadCurve(to: CGPoint(x: 106, y: 35), control: CGPoint(x: 94, y: 20))
}
context.stroke(cap, with: stroke, style: StrokeStyle(lineWidth: lineWidth))
let cross = path { p in
p.move(to: CGPoint(x: 94, y: 24))
p.addLine(to: CGPoint(x: 94, y: 14))
p.move(to: CGPoint(x: 90, y: 18))
p.addLine(to: CGPoint(x: 98, y: 18))
}
context.stroke(cross, with: stroke, style: StrokeStyle(lineWidth: 0.9, lineCap: .round))
let window = path { p in
p.move(to: CGPoint(x: 51, y: 70))
p.addLine(to: CGPoint(x: 51, y: 48))
p.addQuadCurve(to: CGPoint(x: 61, y: 48), control: CGPoint(x: 56, y: 42))
p.addLine(to: CGPoint(x: 61, y: 70))
}
context.stroke(window, with: .color(strokeColor.opacity(0.65)), style: StrokeStyle(lineWidth: 0.8))
}
private func drawChapel(
context: inout GraphicsContext,
strokeColor: Color,
fillColor: Color,
path: ((inout Path) -> Void) -> Path
) {
let stroke = GraphicsContext.Shading.color(strokeColor)
let fill = GraphicsContext.Shading.color(fillColor)
let body = path { p in
p.move(to: CGPoint(x: 40, y: 75))
p.addLine(to: CGPoint(x: 40, y: 46))
p.addLine(to: CGPoint(x: 78, y: 46))
p.addLine(to: CGPoint(x: 78, y: 75))
p.closeSubpath()
}
context.fill(body, with: fill)
context.stroke(body, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let roof = path { p in
p.move(to: CGPoint(x: 35, y: 47))
p.addLine(to: CGPoint(x: 59, y: 24))
p.addLine(to: CGPoint(x: 83, y: 47))
}
context.stroke(roof, with: stroke, style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round))
let cross = path { p in
p.move(to: CGPoint(x: 59, y: 24))
p.addLine(to: CGPoint(x: 59, y: 13))
p.move(to: CGPoint(x: 55, y: 17))
p.addLine(to: CGPoint(x: 63, y: 17))
}
context.stroke(cross, with: stroke, style: StrokeStyle(lineWidth: 1.0, lineCap: .round))
let door = path { p in
p.move(to: CGPoint(x: 55, y: 75))
p.addLine(to: CGPoint(x: 55, y: 60))
p.addQuadCurve(to: CGPoint(x: 65, y: 60), control: CGPoint(x: 60, y: 53))
p.addLine(to: CGPoint(x: 65, y: 75))
}
context.stroke(door, with: stroke, style: StrokeStyle(lineWidth: 0.85))
let window = path { p in
p.addEllipse(in: CGRect(x: 45, y: 55, width: 7, height: 11))
p.addEllipse(in: CGRect(x: 67, y: 55, width: 7, height: 11))
}
context.stroke(window, with: .color(strokeColor.opacity(0.6)), style: StrokeStyle(lineWidth: 0.7))
}
}
struct ChurchMonogram: View {
var church: Church
var size: CGFloat = 34
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: size * 0.28, style: .continuous)
.fill(LP.churchColor(church.colorHex).opacity(0.10))
ChurchGlyph(symbol: church.symbol, tint: LP.churchColor(church.colorHex), lineWidth: 1.6, showGround: false)
.padding(size * 0.16)
}
.frame(width: size, height: size)
.overlay(
RoundedRectangle(cornerRadius: size * 0.28, style: .continuous)
.strokeBorder(LP.churchColor(church.colorHex).opacity(0.22), lineWidth: 0.8)
)
}
}
@@ -0,0 +1,396 @@
import SwiftUI
import LektorenPlanCore
struct TimelineRangePicker: View {
@EnvironmentObject private var model: PlanModel
@State private var draftStart = DayMath.today()
@State private var draftEnd = DayMath.today()
@State private var initialized = false
@State private var dragOrigin: DayRange?
private let minDays = 7
var body: some View {
let bounds = timelineBounds
VStack(spacing: 12) {
header(bounds: bounds)
timeline(bounds: bounds)
.frame(height: 64)
footer
}
.padding(.horizontal, 18)
.padding(.vertical, 14)
.background(
RoundedRectangle(cornerRadius: 16, style: .continuous)
.fill(LP.card)
.shadow(color: .black.opacity(0.035), radius: 10, y: 4)
)
.overlay(
RoundedRectangle(cornerRadius: 16, style: .continuous)
.strokeBorder(LP.line.opacity(0.55), lineWidth: 1)
)
.onAppear {
guard !initialized else { return }
draftStart = model.range.start
draftEnd = model.range.end
initialized = true
}
.onChange(of: model.range) { _, newValue in
draftStart = newValue.start
draftEnd = newValue.end
}
}
private var timelineBounds: 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)
let start = DayMath.date(fromKey: DayMath.key(year: firstYear, month: 1, day: 1)) ?? DayMath.today()
let end = DayMath.date(fromKey: DayMath.key(year: lastYear, month: 12, day: 31)) ?? DayMath.today()
return DayRange(start: start, end: end)
}
private func header(bounds: DayRange) -> some View {
HStack(alignment: .center, spacing: 12) {
HStack(spacing: 7) {
Image(systemName: "calendar.badge.clock")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(LP.accent)
Text("PLANUNGSZEITRAUM")
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.tracking(1.2)
.foregroundStyle(LP.inkTertiary)
}
Text(rangeTitle)
.font(LP.serifSubhead)
.foregroundStyle(LP.ink)
.lineLimit(1)
Spacer(minLength: 8)
presetChip("Dieses Quartal") {
model.setRange(.quarter(containing: DayMath.today()))
}
presetChip("Osterzeit") {
let year = DayMath.year(DayMath.today())
let easter = LiturgicalCalendarEngine.easterSunday(year: year)
model.setRange(DayRange(start: easter, end: LiturgicalCalendarEngine.pentecost(year: year)))
}
presetChip("Weihnachtszeit") {
let year = DayMath.year(DayMath.today())
let christmas = DayMath.date(fromKey: DayMath.key(year: year, month: 12, day: 24)) ?? DayMath.today()
let baptism = LiturgicalCalendarEngine.baptismOfTheLord(year: year + 1)
model.setRange(DayRange(start: christmas, end: baptism))
}
Menu {
Section("Quartale") {
ForEach(nextQuarters(4), id: \.id) { item in
Button(item.label) { model.setRange(item.range) }
}
}
Section("Kirchenjahr") {
Button("Aktuelles Kirchenjahr") { model.setRange(currentChurchYear) }
Button("Osterzeit \(DayMath.year(DayMath.today()))") {
let y = DayMath.year(DayMath.today())
model.setRange(DayRange(
start: LiturgicalCalendarEngine.easterSunday(year: y),
end: LiturgicalCalendarEngine.pentecost(year: y)
))
}
Button("Adventszeit") {
let y = DayMath.year(DayMath.today())
let advent = LiturgicalCalendarEngine.adventStart(year: y)
model.setRange(DayRange(start: advent, end: DayMath.adding(days: -1, to: DayMath.date(fromKey: DayMath.key(year: y, month: 12, day: 25)) ?? advent)))
}
}
Section("Weitere") {
Button("Nächste 90 Tage") { model.setRange(.days(90)) }
Button("Rest des Jahres") {
model.setRange(DayRange(start: DayMath.today(), end: DayMath.endOfYear(DayMath.today())))
}
Button("Gesamtes Kalenderfenster") { model.setRange(bounds) }
}
} label: {
HStack(spacing: 4) {
Image(systemName: "bookmark")
Text("Zeitmarken")
}
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.inkSecondary)
}
.menuStyle(.borderlessButton)
.fixedSize()
}
}
private func timeline(bounds: DayRange) -> some View {
GeometryReader { geo in
let width = geo.size.width
let y: CGFloat = 34
let totalDays = CGFloat(max(1, bounds.dayCount - 1))
let xStart = x(for: draftStart, bounds: bounds, width: width)
let xEnd = x(for: draftEnd, bounds: bounds, width: width)
let spans = seasonSpans(bounds: bounds)
ZStack(alignment: .topLeading) {
// Season background
ForEach(Array(spans.enumerated()), id: \.offset) { _, span in
let x1 = x(for: span.range.start, bounds: bounds, width: width)
let x2 = x(for: span.range.end, bounds: bounds, width: width)
Rectangle()
.fill(Color(hex: span.season.colorHex).opacity(0.11))
.frame(width: max(1, x2 - x1), height: 18)
.offset(x: x1, y: y - 9)
}
// Base line
RoundedRectangle(cornerRadius: 2)
.fill(LP.line.opacity(0.65))
.frame(width: width, height: 2)
.offset(y: y - 1)
// Selected interval
RoundedRectangle(cornerRadius: 4)
.fill(
LinearGradient(colors: [LP.accent.opacity(0.20), LP.gold.opacity(0.22)],
startPoint: .leading, endPoint: .trailing)
)
.frame(width: max(4, xEnd - xStart), height: 22)
.offset(x: xStart, y: y - 11)
.overlay(
RoundedRectangle(cornerRadius: 4)
.strokeBorder(LP.accent.opacity(0.45), lineWidth: 1)
.frame(width: max(4, xEnd - xStart), height: 22)
.offset(x: xStart, y: y - 11)
)
// Quarter ticks and year labels
ForEach(Array(quarterTicks(bounds: bounds).enumerated()), id: \.offset) { _, tick in
let tickX = x(for: tick.date, bounds: bounds, width: width)
Rectangle()
.fill(tick.isYear ? LP.inkTertiary.opacity(0.45) : LP.line.opacity(0.9))
.frame(width: 1, height: tick.isYear ? 30 : 20)
.offset(x: tickX, y: y - (tick.isYear ? 15 : 10))
if tick.isYear {
Text(String(DayMath.year(tick.date)))
.font(.system(size: 8.5, weight: .semibold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
.offset(x: tickX + 4, y: 3)
}
}
// Month labels around selection
if width > 500 {
Text(DayMath.mediumString(draftStart))
.font(.system(size: 9, weight: .semibold, design: .rounded))
.foregroundStyle(LP.accent)
.offset(x: min(max(0, xStart - 26), width - 100), y: y + 18)
Text(DayMath.mediumString(draftEnd))
.font(.system(size: 9, weight: .semibold, design: .rounded))
.foregroundStyle(LP.gold)
.offset(x: min(max(0, xEnd - 26), width - 100), y: y + 18)
}
// Left handle
handle(color: LP.accent, help: "Beginn: \(DayMath.longString(draftStart))\nZiehen zum Ändern")
.position(x: xStart, y: y)
.gesture(dragGesture(handle: .start, bounds: bounds, width: width, totalDays: totalDays))
// Right handle
handle(color: LP.gold, help: "Ende: \(DayMath.longString(draftEnd))\nZiehen zum Ändern")
.position(x: xEnd, y: y)
.gesture(dragGesture(handle: .end, bounds: bounds, width: width, totalDays: totalDays))
}
}
}
private var footer: some View {
HStack(spacing: 14) {
HStack(spacing: 5) {
Circle().fill(LP.accent).frame(width: 6, height: 6)
Text(DayMath.mediumString(draftStart))
}
HStack(spacing: 5) {
Circle().fill(LP.gold).frame(width: 6, height: 6)
Text(DayMath.mediumString(draftEnd))
}
Hairline().frame(width: 18)
Text("\(draftRange.dayCount) Tage")
.foregroundStyle(LP.inkSecondary)
Text("·")
.foregroundStyle(LP.inkTertiary)
Text("\(model.stats.serviceCount) Gottesdienste")
.foregroundStyle(LP.inkSecondary)
Text("·")
.foregroundStyle(LP.inkTertiary)
Text("\(Int(model.stats.coverageRate * 100)) % besetzt")
.foregroundStyle(model.stats.openSlots == 0 ? LP.success : LP.open)
Spacer()
Text("Ziehen oder Zeitmarke wählen")
.foregroundStyle(LP.inkTertiary)
}
.font(.system(size: 9.5, weight: .medium, design: .rounded))
}
private var draftRange: DayRange {
DayRange(start: draftStart, end: draftEnd)
}
private var rangeTitle: String {
"\(DayMath.mediumString(draftStart)) – \(DayMath.mediumString(draftEnd))"
}
private func presetChip(_ title: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
Text(title)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(LP.inkSecondary)
.padding(.horizontal, 9)
.padding(.vertical, 4)
.background(Capsule().fill(LP.cardMuted))
.overlay(Capsule().strokeBorder(LP.line.opacity(0.7), lineWidth: 0.7))
}
.buttonStyle(.plain)
}
private func handle(color: Color, help: String) -> some View {
VStack(spacing: 0) {
Circle()
.fill(color)
.frame(width: 9, height: 9)
.overlay(Circle().strokeBorder(.white.opacity(0.8), lineWidth: 1.4))
RoundedRectangle(cornerRadius: 3)
.fill(color)
.frame(width: 5, height: 24)
.overlay(
VStack(spacing: 2) {
ForEach(0..<3, id: \.self) { _ in
Capsule().fill(.white.opacity(0.65)).frame(width: 1.5, height: 2)
}
}
)
Circle()
.fill(color)
.frame(width: 5, height: 5)
.opacity(0.5)
}
.shadow(color: color.opacity(0.35), radius: 4, y: 2)
.help(help)
}
private enum DragHandle { case start, end }
private func dragGesture(handle: DragHandle, bounds: DayRange, width: CGFloat, totalDays: CGFloat) -> some Gesture {
DragGesture(minimumDistance: 0)
.onChanged { value in
if dragOrigin == nil {
dragOrigin = DayRange(start: draftStart, end: draftEnd)
}
guard let origin = dragOrigin else { return }
let dayDelta = Int((value.translation.width / max(1, width)) * totalDays)
if handle == .start {
let maxStart = DayMath.adding(days: -(minDays - 1), to: origin.end)
var newStart = DayMath.adding(days: dayDelta, to: origin.start)
if newStart < bounds.start { newStart = bounds.start }
if newStart > maxStart { newStart = maxStart }
draftStart = DayMath.normalize(newStart)
} else {
let minEnd = DayMath.adding(days: minDays - 1, to: origin.start)
var newEnd = DayMath.adding(days: dayDelta, to: origin.end)
if newEnd > bounds.end { newEnd = bounds.end }
if newEnd < minEnd { newEnd = minEnd }
draftEnd = DayMath.normalize(newEnd)
}
}
.onEnded { _ in
dragOrigin = nil
model.setRange(draftRange)
}
}
private func x(for date: Date, bounds: DayRange, width: CGFloat) -> CGFloat {
let day = DayMath.daysBetween(bounds.start, date)
let fraction = CGFloat(day) / CGFloat(max(1, bounds.dayCount - 1))
return min(width, max(0, fraction * width))
}
private struct SeasonSpan {
var range: DayRange
var season: LiturgicalSeason
}
private func seasonSpans(bounds: DayRange) -> [SeasonSpan] {
var spans: [SeasonSpan] = []
var currentSeason: LiturgicalSeason?
var spanStart: Date?
var previous: Date?
for day in bounds.days {
let season = LiturgicalCalendarEngine.season(for: day)
if season != currentSeason {
if let currentSeason, let spanStart, let previous {
spans.append(SeasonSpan(range: DayRange(start: spanStart, end: previous), season: currentSeason))
}
currentSeason = season
spanStart = day
}
previous = day
}
if let currentSeason, let spanStart, let previous {
spans.append(SeasonSpan(range: DayRange(start: spanStart, end: previous), season: currentSeason))
}
return spans
}
private struct QuarterTick {
var date: Date
var isYear: Bool
}
private func quarterTicks(bounds: DayRange) -> [QuarterTick] {
var ticks: [QuarterTick] = []
var year = DayMath.year(bounds.start)
while year <= DayMath.year(bounds.end) {
for month in [1, 4, 7, 10] {
if let date = DayMath.date(fromKey: DayMath.key(year: year, month: month, day: 1)),
bounds.contains(date) {
ticks.append(QuarterTick(date: date, isYear: month == 1))
}
}
year += 1
}
return ticks
}
private struct QuarterPreset: Identifiable {
var id: String { label }
var label: String
var range: DayRange
}
private func nextQuarters(_ count: Int) -> [QuarterPreset] {
let today = DayMath.today()
return (0..<count).map { offset in
let base = DayMath.adding(months: offset * 3, to: today)
let range = DayRange.quarter(containing: base)
let q = DayMath.quarter(range.start)
return QuarterPreset(label: "Q\(q) \(DayMath.year(range.start))", range: range)
}
}
private var currentChurchYear: DayRange {
let today = DayMath.today()
let y = DayMath.year(today)
let thisAdvent = LiturgicalCalendarEngine.adventStart(year: y)
if today < thisAdvent {
return DayRange(
start: LiturgicalCalendarEngine.adventStart(year: y - 1),
end: LiturgicalCalendarEngine.christKing(year: y)
)
}
return DayRange(
start: thisAdvent,
end: LiturgicalCalendarEngine.christKing(year: y + 1)
)
}
}
@@ -0,0 +1,80 @@
import SwiftUI
import AppKit
import LektorenPlanCore
@main
struct LektorenPlanApp: App {
@StateObject private var model = PlanModel()
var body: some Scene {
WindowGroup("LektorenPlan") {
RootView()
.environmentObject(model)
.task {
await SnapshotCapture.runIfRequested(model: model)
}
}
.windowStyle(.hiddenTitleBar)
.defaultSize(width: 1480, height: 930)
.windowResizability(.contentMinSize)
.commands {
AppCommands(model: model)
}
}
}
struct AppCommands: Commands {
let model: PlanModel
var body: some Commands {
CommandGroup(replacing: .newItem) {}
CommandGroup(after: .saveItem) {
Divider()
Button("Planungsabschnitt exportieren…") {
model.exportInteractive(scope: .plan)
}
.keyboardShortcut("e", modifiers: [.command, .shift])
Button("Ressourcen exportieren…") {
model.exportInteractive(scope: .resources)
}
Button("Importieren…") {
model.importInteractive()
}
.keyboardShortcut("i", modifiers: [.command, .shift])
Divider()
Button("PDF-Vorschau…") {
model.createPDFPreview()
}
.keyboardShortcut("p", modifiers: [.command, .shift])
Button("Drucken…") {
model.printPDF()
}
.keyboardShortcut("p", modifiers: .command)
}
CommandMenu("Planung") {
Button("Offene Dienste besetzen") {
_ = model.autoPlan(replaceExisting: false)
}
.keyboardShortcut("r", modifiers: .command)
Button("Liturgischen Kalender aktualisieren") {
Task { await model.syncLiturgy() }
}
.keyboardShortcut("u", modifiers: [.command, .shift])
Divider()
Button("Gottesdienste für Zeitraum erzeugen") {
model.generateServices()
}
}
CommandMenu("Ansicht") {
ForEach(AppSection.allCases) { section in
Button(section.title) {
model.section = section
}
.keyboardShortcut(KeyEquivalent(Character(String(section.keyboardNumber))), modifiers: .command)
}
}
}
}
@@ -0,0 +1,525 @@
import AppKit
import CoreGraphics
import LektorenPlanCore
/// Renders a printable plan for a range. The output is A4 landscape and paginates
/// automatically, repeating the header and column titles on every page.
enum PlanPDFRenderer {
private static let pageWidth: CGFloat = 842
private static let pageHeight: CGFloat = 595
private static let margin: CGFloat = 24
private static let headerHeight: CGFloat = 76
private static let columnHeaderHeight: CGFloat = 26
private static let footerHeight: CGFloat = 20
private static let dateWidth: CGFloat = 50
private static let liturgyWidth: CGFloat = 164
private static let columnGap: CGFloat = 4
// MARK: - Colours
private static let ink = NSColor(calibratedRed: 0.12, green: 0.135, blue: 0.155, alpha: 1)
private static let secondaryInk = NSColor(calibratedRed: 0.38, green: 0.385, blue: 0.39, alpha: 1)
private static let tertiaryInk = NSColor(calibratedRed: 0.52, green: 0.51, blue: 0.49, alpha: 1)
private static let lineColor = NSColor(calibratedRed: 0.845, green: 0.825, blue: 0.79, alpha: 1)
private static let accent = NSColor(calibratedRed: 0.18, green: 0.36, blue: 0.34, alpha: 1)
private static let gold = NSColor(calibratedRed: 0.72, green: 0.53, blue: 0.23, alpha: 1)
private static let burgundy = NSColor(calibratedRed: 0.49, green: 0.24, blue: 0.29, alpha: 1)
private static let sundayWash = NSColor(calibratedRed: 0.985, green: 0.955, blue: 0.885, alpha: 1)
private static let feastWash = NSColor(calibratedRed: 0.998, green: 0.955, blue: 0.79, alpha: 1)
private static let openColor = NSColor(calibratedRed: 0.70, green: 0.42, blue: 0.13, alpha: 1)
// MARK: - Fonts
private static func serif(_ size: CGFloat, bold: Bool = false) -> NSFont {
let name = bold ? "NewYork-Semibold" : "NewYork-Regular"
return NSFont(name: name, size: size) ?? NSFont.systemFont(ofSize: size, weight: bold ? .semibold : .regular)
}
private static func sans(_ size: CGFloat, weight: NSFont.Weight = .regular) -> NSFont {
NSFont.systemFont(ofSize: size, weight: weight)
}
// MARK: - Render
static func render(
range: DayRange,
rows: [DayPlanRow],
churches: [Church],
people: [String: Person],
generatedAt: Date
) -> Data {
let data = NSMutableData()
var mediaBox = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
guard let consumer = CGDataConsumer(data: data as CFMutableData),
let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)
else {
return Data()
}
storedContext = context
defer { storedContext = nil }
let sortedRows = rows.sorted { $0.date < $1.date }
let churchWidth = (pageWidth - margin * 2 - dateWidth - liturgyWidth - columnGap * 5) / 4
let contentTop = margin + headerHeight + columnHeaderHeight + 4
let contentBottom = pageHeight - margin - footerHeight
var pageIndex = 0
func beginPage() {
context.beginPDFPage(nil)
context.saveGState()
// Use a top-left origin for the whole page. This keeps the row layout
// (header at the top, rows flowing downwards) straightforward.
context.translateBy(x: 0, y: pageHeight)
context.scaleBy(x: 1, y: -1)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
}
func endPage() {
drawFooter(pageIndex: pageIndex, range: range)
NSGraphicsContext.restoreGraphicsState()
context.restoreGState()
context.endPDFPage()
pageIndex += 1
}
beginPage()
drawHeader(range: range, generatedAt: generatedAt)
drawColumnHeader(churches: churches, churchWidth: churchWidth)
var cursorY = contentTop
for (index, row) in sortedRows.enumerated() {
let height = rowHeight(row: row, churchWidth: churchWidth, people: people)
if cursorY + height > contentBottom {
endPage()
beginPage()
drawHeader(range: range, generatedAt: generatedAt, continuation: true)
drawColumnHeader(churches: churches, churchWidth: churchWidth)
cursorY = contentTop
}
drawRow(
row: row,
y: cursorY,
height: height,
churches: churches,
churchWidth: churchWidth,
people: people
)
cursorY += height
// A light separator is enough; keep the page airy.
if index < sortedRows.count - 1 {
context.setStrokeColor(lineColor.withAlphaComponent(0.55).cgColor)
context.setLineWidth(0.5)
context.move(to: CGPoint(x: margin, y: cursorY))
context.addLine(to: CGPoint(x: pageWidth - margin, y: cursorY))
context.strokePath()
}
}
if sortedRows.isEmpty {
let text = "Für den gewählten Zeitraum sind keine Gottesdienste hinterlegt."
drawText(
text,
in: CGRect(x: margin, y: contentTop + 12, width: pageWidth - margin * 2, height: 30),
font: serif(15),
color: secondaryInk
)
}
endPage()
context.closePDF()
return data as Data
}
// MARK: - Page furniture
private static func drawHeader(range: DayRange, generatedAt: Date, continuation: Bool = false) {
let top = margin
drawText(
"LEKTORENPLAN · PFARREIENGEMEINSCHAFT BAD GODESBERG",
in: CGRect(x: margin, y: top, width: 420, height: 12),
font: sans(7.5, weight: .bold),
color: accent
)
drawText(
continuation ? "Gottesdienstplan · Fortsetzung" : "Gottesdienstplan",
in: CGRect(x: margin, y: top + 13, width: 500, height: 24),
font: serif(21, bold: true),
color: ink
)
drawText(
range.longTitle,
in: CGRect(x: margin, y: top + 40, width: 460, height: 14),
font: sans(10.5),
color: secondaryInk
)
let rightX = pageWidth - margin - 230
drawText(
"Erstellt am \(DayMath.mediumString(generatedAt))",
in: CGRect(x: rightX, y: top, width: 230, height: 12),
font: sans(8.5),
color: tertiaryInk,
alignment: .right
)
drawText(
"Liturgischer Kalender: Erzbistum Köln",
in: CGRect(x: rightX, y: top + 15, width: 230, height: 12),
font: sans(8),
color: tertiaryInk,
alignment: .right
)
drawText(
"Daten von www.eucharistiefeier.de",
in: CGRect(x: rightX, y: top + 28, width: 230, height: 12),
font: sans(7.5),
color: tertiaryInk,
alignment: .right
)
contextLine(y: top + headerHeight - 6)
}
private static func drawColumnHeader(churches: [Church], churchWidth: CGFloat) {
let y = margin + headerHeight
let height = columnHeaderHeight
let background = CGRect(x: margin, y: y, width: pageWidth - margin * 2, height: height)
contextFill(background, color: NSColor(calibratedWhite: 0.96, alpha: 1))
var x = margin + 6
drawText("TAG", in: CGRect(x: x, y: y + 8, width: dateWidth - 6, height: 10),
font: sans(6.5, weight: .bold), color: tertiaryInk)
x += dateWidth
drawText("LITURGIE & LESUNGEN", in: CGRect(x: x, y: y + 8, width: liturgyWidth, height: 10),
font: sans(6.5, weight: .bold), color: tertiaryInk)
x += liturgyWidth + columnGap
for church in churches.prefix(4) {
let color = NSColor(hexString: church.colorHex) ?? accent
drawText(
church.name,
in: CGRect(x: x + 5, y: y + 4, width: churchWidth - 10, height: 12),
font: serif(9.5, bold: true),
color: color
)
drawText(
church.address,
in: CGRect(x: x + 5, y: y + 15, width: churchWidth - 10, height: 8),
font: sans(6, weight: .regular),
color: tertiaryInk
)
x += churchWidth + columnGap
}
contextLine(y: y + height)
}
private static func drawFooter(pageIndex: Int, range: DayRange) {
let y = pageHeight - margin - footerHeight
contextLine(y: y + 6)
drawText(
"LektorenPlan · \(range.shortTitle)",
in: CGRect(x: margin, y: y + 10, width: 300, height: 12),
font: sans(7),
color: tertiaryInk
)
drawText(
"Seite \(pageIndex + 1)",
in: CGRect(x: pageWidth - margin - 90, y: y + 10, width: 90, height: 12),
font: sans(7),
color: tertiaryInk,
alignment: .right
)
}
// MARK: - Rows
private static func rowHeight(
row: DayPlanRow,
churchWidth: CGFloat,
people: [String: Person]
) -> CGFloat {
var tallest: CGFloat = 46
if let day = row.liturgicalDay {
var liturgyHeight: CGFloat = 14
liturgyHeight += measuredHeight(day.displayTitle, font: serif(10, bold: true), width: liturgyWidth - 8, maxLines: 3)
if !day.readings.isEmpty {
liturgyHeight += measuredHeight(day.readings.shortLabel, font: sans(7), width: liturgyWidth - 8, maxLines: 3) + 2
}
tallest = max(tallest, liturgyHeight + 8)
}
for church in row.services.map(\.church).uniqued(by: \.id) {
let services = row.services.filter { $0.church.id == church.id }
var height: CGFloat = 5
for service in services {
height += 12
for role in Role.allCases where service.service.requiredCount(for: role) > 0 {
height += 9
}
height += 3
}
tallest = max(tallest, height + 4)
}
return min(tallest, 150)
}
private static func drawRow(
row: DayPlanRow,
y: CGFloat,
height: CGFloat,
churches: [Church],
churchWidth: CGFloat,
people: [String: Person]
) {
let isSunday = row.liturgicalDay?.isSunday == true || DayMath.isSunday(row.date)
let isFeast = row.liturgicalDay?.isHighFeast == true
let isHoliday = row.liturgicalDay?.isObligation == true && !isSunday
let rowRect = CGRect(x: margin, y: y, width: pageWidth - margin * 2, height: height)
if isFeast {
contextFill(rowRect, color: feastWash)
} else if isSunday || isHoliday {
contextFill(rowRect, color: sundayWash)
}
var x = margin
// Date cell
let weekday = DayMath.shortWeekdayName(row.date).uppercased()
drawText(
weekday,
in: CGRect(x: x + 6, y: y + 6, width: dateWidth - 6, height: 9),
font: sans(6.5, weight: .bold),
color: isSunday ? burgundy : tertiaryInk
)
drawText(
"\(DayMath.dayNumber(row.date)).",
in: CGRect(x: x + 6, y: y + 14, width: dateWidth - 6, height: 18),
font: serif(15, bold: true),
color: isFeast ? gold : (isSunday ? burgundy : ink)
)
drawText(
DayMath.shortMonthName(row.date),
in: CGRect(x: x + 6, y: y + 31, width: dateWidth - 6, height: 9),
font: sans(6.5),
color: tertiaryInk
)
if isSunday {
drawText("SONNTAG", in: CGRect(x: x + 6, y: y + 41, width: dateWidth, height: 8),
font: sans(5.5, weight: .bold), color: burgundy.withAlphaComponent(0.85))
}
x += dateWidth
// Liturgy cell
var textY = y + 5
if let day = row.liturgicalDay {
let badge: String?
if day.isHighFeast {
badge = "HOCHFEST"
} else if day.rank == .feast {
badge = "FEST"
} else if day.rank == .obligatoryMemorial {
badge = "GEDENKTAG"
} else if day.isObligation && !day.isSunday {
badge = "GEBOTEN"
} else {
badge = nil
}
if let badge {
let color = day.isHighFeast ? gold : (day.rank == .feast ? burgundy : accent)
drawBadge(badge, x: x + 4, y: textY, color: color)
textY += 12
}
let titleHeight = drawText(
day.displayTitle,
in: CGRect(x: x + 4, y: textY, width: liturgyWidth - 8, height: height - 20),
font: serif(9.5, bold: day.isFeast),
color: isFeast ? ink : (isSunday ? burgundy : ink),
maxLines: 3
)
textY += titleHeight + 2
if !day.readings.isEmpty {
drawText(
day.readings.shortLabel,
in: CGRect(x: x + 4, y: textY, width: liturgyWidth - 8, height: height - (textY - y) - 4),
font: sans(6.5),
color: secondaryInk,
maxLines: 3
)
}
}
x += liturgyWidth + columnGap
// Church columns
for church in churches.prefix(4) {
let services = row.services.filter { $0.church.id == church.id }
var serviceY = y + 4
for service in services {
let color = NSColor(hexString: church.colorHex) ?? accent
drawText(
"\(service.service.timeLabel) \(service.service.title)",
in: CGRect(x: x + 5, y: serviceY, width: churchWidth - 10, height: 11),
font: sans(7, weight: .semibold),
color: color,
maxLines: 1
)
serviceY += 11
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"
let value = names.isEmpty ? "offen" : names.joined(separator: ", ")
drawText(
"\(prefix): \(value)",
in: CGRect(x: x + 7, y: serviceY, width: churchWidth - 12, height: 9),
font: sans(6.5, weight: names.isEmpty ? .semibold : .regular),
color: names.isEmpty ? openColor : secondaryInk,
maxLines: 2
)
serviceY += 9
}
serviceY += 3
if serviceY > y + height - 6 { break }
}
// Church column separator
context.setStrokeColor(lineColor.withAlphaComponent(0.4).cgColor)
context.setLineWidth(0.4)
context.move(to: CGPoint(x: x, y: y + 3))
context.addLine(to: CGPoint(x: x, y: y + height - 3))
context.strokePath()
x += churchWidth + columnGap
}
}
// MARK: - Drawing helpers
private static func drawBadge(_ text: String, x: CGFloat, y: CGFloat, color: NSColor) {
let font = sans(6, weight: .bold)
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: NSColor.white
]
let size = (text as NSString).size(withAttributes: attributes)
let rect = CGRect(x: x, y: y, width: size.width + 8, height: 9)
let path = NSBezierPath(roundedRect: rect, xRadius: 3, yRadius: 3)
color.setFill()
path.fill()
(text as NSString).draw(
at: CGPoint(x: rect.minX + 4, y: rect.minY + 1.2),
withAttributes: attributes
)
}
@discardableResult
private static func drawText(
_ text: String,
in rect: CGRect,
font: NSFont,
color: NSColor,
alignment: NSTextAlignment = .left,
maxLines: Int = 1
) -> CGFloat {
guard !text.isEmpty else { return 0 }
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = alignment
paragraph.lineBreakMode = maxLines > 1 ? .byWordWrapping : .byTruncatingTail
paragraph.lineSpacing = 0.5
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: color,
.paragraphStyle: paragraph
]
let attributed = NSAttributedString(string: text, attributes: attributes)
let measured = attributed.boundingRect(
with: CGSize(width: rect.width, height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading]
)
let lineHeight = font.pointSize * 1.22
let maxHeight = lineHeight * CGFloat(maxLines)
let drawHeight = min(measured.height, maxHeight)
attributed.draw(
with: CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: max(drawHeight, lineHeight)),
options: [.usesLineFragmentOrigin, .usesFontLeading]
)
return min(measured.height, maxHeight)
}
private static func measuredHeight(
_ text: String,
font: NSFont,
width: CGFloat,
maxLines: Int
) -> CGFloat {
let attributes: [NSAttributedString.Key: Any] = [.font: font]
let measured = (text as NSString).boundingRect(
with: CGSize(width: width, height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attributes
)
return min(measured.height, font.pointSize * 1.22 * CGFloat(maxLines))
}
private static func contextLine(y: CGFloat) {
context.setStrokeColor(lineColor.withAlphaComponent(0.75).cgColor)
context.setLineWidth(0.7)
context.move(to: CGPoint(x: margin, y: y))
context.addLine(to: CGPoint(x: pageWidth - margin, y: y))
context.strokePath()
}
private static func contextFill(_ rect: CGRect, color: NSColor) {
context.setFillColor(color.cgColor)
context.fill(rect)
}
/// The drawing context is stored in a task-local-ish static for the duration of a render.
/// PDF rendering is synchronous on the main thread, so this is safe in practice.
nonisolated(unsafe) private static var storedContext: CGContext?
private static var context: CGContext {
storedContext ?? CGContext(data: nil, width: 1, height: 1, bitsPerComponent: 8,
bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
}
}
private extension DayRange {
var longTitle: String {
"\(DayMath.longString(start)) bis \(DayMath.longString(end)) · \(dayCount) Tage"
}
}
private extension Array {
func uniqued<Key: Hashable>(by key: (Element) -> Key) -> [Element] {
var seen: Set<Key> = []
return filter { element in
let value = key(element)
if seen.contains(value) { return false }
seen.insert(value)
return true
}
}
}
private extension NSColor {
convenience init?(hexString: String) {
let cleaned = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
guard cleaned.count == 6, let value = UInt64(cleaned, radix: 16) else { return nil }
self.init(
calibratedRed: CGFloat((value >> 16) & 0xFF) / 255,
green: CGFloat((value >> 8) & 0xFF) / 255,
blue: CGFloat(value & 0xFF) / 255,
alpha: 1
)
}
}
+880
View File
@@ -0,0 +1,880 @@
import SwiftUI
import AppKit
import UniformTypeIdentifiers
import PDFKit
import LektorenPlanCore
enum AppSection: String, CaseIterable, Identifiable, Hashable {
case planning
case serviceOrder
case team
case statistics
case exchange
case settings
var id: String { rawValue }
var title: String {
switch self {
case .planning: "Kalender & Planung"
case .serviceOrder: "Gottesdienstordnung"
case .team: "Lektoren & Helfer"
case .statistics: "Statistik"
case .exchange: "Austausch"
case .settings: "Einstellungen"
}
}
var shortTitle: String {
switch self {
case .planning: "Planung"
case .serviceOrder: "Ordnung"
case .team: "Team"
case .statistics: "Statistik"
case .exchange: "Austausch"
case .settings: "Einstellungen"
}
}
var icon: String {
switch self {
case .planning: "calendar"
case .serviceOrder: "building.columns"
case .team: "person.2"
case .statistics: "chart.xyaxis.line"
case .exchange: "arrow.left.arrow.right"
case .settings: "gearshape"
}
}
var keyboardNumber: Int {
switch self {
case .planning: 1
case .serviceOrder: 2
case .team: 3
case .statistics: 4
case .exchange: 5
case .settings: 6
}
}
}
enum PlanFilter: String, CaseIterable, Identifiable {
case all
case services
case open
var id: String { rawValue }
var title: String {
switch self {
case .all: "Alle Tage"
case .services: "Mit Gottesdiensten"
case .open: "Nur offene"
}
}
}
struct PersonEditorRequest: Identifiable {
let id = UUID()
var person: Person?
var presetRole: Role? = nil
}
struct TemplateEditorRequest: Identifiable {
let id = UUID()
var template: ServiceTemplate?
var churchID: String?
}
struct SpecialServiceRequest: Identifiable {
let id = UUID()
var churchID: String?
var date: Date = DayMath.today()
var service: ServiceOccurrence? = nil
}
struct ServiceDetailRequest: Identifiable {
let id = UUID()
var serviceID: String
}
struct ImportPreview: Identifiable {
let id = UUID()
var exchange: PlanExchange
var data: Data
var sourceName: String
}
struct PDFPreview: Identifiable {
let id = UUID()
var data: Data
var title: String
var filename: String
}
struct CandidateSuggestion: Identifiable {
var person: Person
var score: Double
var warnings: [String]
var blocked: Bool
var preferred: Bool
var totalAssignments: Int
var id: String { person.id }
}
@MainActor
final class PlanModel: ObservableObject {
let db: AppDatabase
@Published var section: AppSection = .planning
@Published var range: DayRange = .quarter(containing: DayMath.today())
@Published var churches: [Church] = []
@Published var people: [Person] = []
@Published var absences: [Absence] = []
@Published var templates: [ServiceTemplate] = []
@Published var exceptions: [ServiceException] = []
@Published var services: [ServiceOccurrence] = []
@Published var assignments: [Assignment] = []
@Published var specialServices: [ServiceOccurrence] = []
@Published var liturgicalDays: [String: LiturgicalDay] = [:]
@Published var peopleByID: [String: Person] = [:]
@Published var churchByID: [String: Church] = [:]
@Published var rows: [DayPlanRow] = []
@Published var stats: RangeStatistics = .empty
@Published var lastSync: Date?
@Published var isSyncing = false
@Published var isPlanning = false
@Published var syncMessage: String = ""
@Published var alertMessage: String?
@Published var alertTitle: String = "Hinweis"
@Published var toast: Toast?
@Published var filter: PlanFilter = .all
@Published var searchText: String = ""
@Published var showOnlySundaysAndFeasts: Bool = false
@Published var personEditor: PersonEditorRequest?
@Published var templateEditor: TemplateEditorRequest?
@Published var specialServiceEditor: SpecialServiceRequest?
@Published var serviceDetail: ServiceDetailRequest?
@Published var planResult: PlanResult?
@Published var importPreview: ImportPreview?
@Published var pdfPreview: PDFPreview?
@Published var databasePath: String
@Published var startupWarning: String?
private var toastTask: Task<Void, Never>?
init(database: AppDatabase? = nil) {
let resolved: AppDatabase
var warning: String?
if let database {
resolved = database
} else {
do {
resolved = try AppDatabase(path: AppDatabase.defaultPath())
} catch {
let fallback = try! AppDatabase.makeInMemory(seedDemo: true)
resolved = fallback
warning = "Die Datenbank konnte nicht geöffnet werden. Es wird eine temporäre In-Memory-Datenbank verwendet.\n\(error.localizedDescription)"
}
}
self.db = resolved
self.databasePath = resolved.path
self.startupWarning = warning
if let startKey = resolved.setting("rangeStart"),
let endKey = resolved.setting("rangeEnd"),
let start = DayMath.date(fromKey: startKey),
let end = DayMath.date(fromKey: endKey),
end >= start {
self.range = DayRange(start: start, end: end)
} else {
self.range = .quarter(containing: DayMath.today())
}
if let value = resolved.setting("showOnlySundaysAndFeasts") {
self.showOnlySundaysAndFeasts = value == "1"
}
loadAll()
if let warning { alertMessage = warning; alertTitle = "Eingeschränkter Betrieb" }
}
// MARK: - Loading
func loadAll() {
do {
ensureLiturgicalCoverage()
churches = try db.churches().sorted { $0.sortIndex < $1.sortIndex }
people = try db.people()
peopleByID = Dictionary(uniqueKeysWithValues: people.map { ($0.id, $0) })
churchByID = Dictionary(uniqueKeysWithValues: churches.map { ($0.id, $0) })
absences = try db.absences()
templates = try db.templates()
exceptions = try db.exceptions()
services = try db.services(in: range)
assignments = try db.assignments(in: range)
specialServices = try db.specialServices()
liturgicalDays = Dictionary(uniqueKeysWithValues: try db.liturgicalDays(in: range).map { ($0.dateKey, $0) })
if let raw = db.setting("lastLiturgicalSync") {
lastSync = ISO8601DateFormatter().date(from: raw)
}
rebuildRows()
stats = StatisticsCalculator.compute(
range: range,
services: services,
assignments: assignments,
people: people,
churches: churches,
absences: absences
)
} catch {
alertTitle = "Daten konnten nicht geladen werden"
alertMessage = error.localizedDescription
}
}
private func ensureLiturgicalCoverage() {
do {
let existing = try db.liturgicalDays(in: range)
let keys = Set(existing.map(\.dateKey))
var missing: [LiturgicalDay] = []
for date in range.days where !keys.contains(DayMath.key(date)) {
missing.append(LiturgicalCalendarEngine.localDay(for: date))
}
if !missing.isEmpty {
try db.upsert(liturgicalDays: missing)
}
} catch {
// Reading the local fallback must never block the rest of the UI.
print("Liturgical coverage failed: \(error)")
}
}
private func rebuildRows() {
let servicesByDay = Dictionary(grouping: services, by: \.dateKey)
let assignmentsByService = Dictionary(grouping: assignments, by: \.serviceID)
rows = range.days.map { date in
let key = DayMath.key(date)
let dayServices = (servicesByDay[key] ?? [])
.sorted { $0.timeMinutes < $1.timeMinutes }
.compactMap { service -> ServiceWithAssignments? in
guard let church = churchByID[service.churchID] else { return nil }
let serviceAssignments = (assignmentsByService[service.id] ?? [])
.sorted { $0.role == .lector && $1.role == .helper }
return ServiceWithAssignments(service: service, church: church, assignments: serviceAssignments)
}
return DayPlanRow(date: date, liturgicalDay: liturgicalDays[key], services: dayServices)
}
}
// MARK: - Range
func setRange(_ newRange: DayRange) {
guard newRange != range else { return }
range = newRange
db.setSetting("rangeStart", value: DayMath.key(newRange.start))
db.setSetting("rangeEnd", value: DayMath.key(newRange.end))
loadAll()
}
func setSundayFilter(_ enabled: Bool) {
showOnlySundaysAndFeasts = enabled
db.setSetting("showOnlySundaysAndFeasts", value: enabled ? "1" : "0")
}
var filteredRows: [DayPlanRow] {
let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return rows.filter { row in
if showOnlySundaysAndFeasts {
let isSpecialDay = row.liturgicalDay?.isSunday == true || row.liturgicalDay?.isObligation == true || row.liturgicalDay?.isFeast == true
if !isSpecialDay { return false }
}
switch filter {
case .all:
break
case .services:
if !row.hasServices { return false }
case .open:
if row.openSlots == 0 { return false }
}
guard !query.isEmpty else { return true }
if row.liturgicalDay?.title.lowercased().contains(query) == true { return true }
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 service.service.title.lowercased().contains(query) { return true }
for assignment in service.assignments {
if let person = peopleByID[assignment.personID],
person.fullName.lowercased().contains(query) {
return true
}
}
}
return false
}
}
var openSlotCount: Int { stats.openSlots }
var rangeServiceCount: Int { stats.serviceCount }
var fullyStaffedServiceCount: Int {
rows.reduce(0) { total, row in
total + row.services.filter(\.isFullyStaffed).count
}
}
var lectorCount: Int { people.filter { $0.active && $0.roles.contains(.lector) }.count }
var helperCount: Int { people.filter { $0.active && $0.roles.contains(.helper) }.count }
// MARK: - Planning
func autoPlan(replaceExisting: Bool) -> PlanResult? {
guard !isPlanning else { return nil }
isPlanning = true
defer { isPlanning = false }
do {
let rangeServices = try db.services(in: range)
let existing = try db.assignments(in: range)
let options = PlannerOptions(
replaceExisting: replaceExisting,
respectPreferredWeekdays: db.setting("respectPreferredWeekdays") != "0",
weightFairness: Double(db.setting("fairnessWeight") ?? "") ?? 2.2,
maxAssignmentsPerDay: 1
)
let planner = ServicePlanner(
people: people,
absences: absences,
services: rangeServices,
existingAssignments: existing,
churches: churches,
options: options
)
let result = planner.plan()
if result.filledCount > 0 || replaceExisting {
try db.savePlan(result.assignments, in: range, replaceUnlocked: replaceExisting)
}
loadAll()
planResult = result
return result
} catch {
alertTitle = "Planung fehlgeschlagen"
alertMessage = error.localizedDescription
return nil
}
}
func autoFill(serviceID: String) {
do {
guard let service = try db.service(id: serviceID) else { return }
let dayRange = DayRange(start: service.date, end: service.date)
let existing = try db.assignments(in: dayRange)
let servicesOfDay = try db.services(in: dayRange)
let planner = ServicePlanner(
people: people,
absences: absences,
services: [service],
existingAssignments: existing.filter { $0.serviceID == serviceID },
churches: churches,
options: PlannerOptions(replaceExisting: false, respectPreferredWeekdays: false)
)
let result = planner.plan()
_ = servicesOfDay
try db.savePlan(result.assignments, in: dayRange, replaceUnlocked: false)
loadAll()
if result.unfilled.isEmpty {
showToast("Gottesdienst vollständig besetzt.", kind: .success)
} else {
showToast("\(result.unfilled.count) Lücke(n) konnten nicht besetzt werden.", kind: .warning)
}
} catch {
alertTitle = "Planung fehlgeschlagen"
alertMessage = error.localizedDescription
}
}
func assign(serviceID: String, role: Role, personID: String?) {
do {
try db.setAssignment(serviceID: serviceID, role: role, personID: personID)
loadAll()
if let personID, let person = peopleByID[personID] {
showToast("\(person.fullName) als \(role.title) eingetragen.", kind: .success)
} else {
showToast("Dienst freigegeben.", kind: .info)
}
} catch {
alertTitle = "Zuweisung fehlgeschlagen"
alertMessage = error.localizedDescription
}
}
func toggleAssignmentLock(_ assignment: Assignment) {
do {
try db.toggleAssignmentLock(id: assignment.id)
loadAll()
} catch {
alertTitle = "Sperre konnte nicht geändert werden"
alertMessage = error.localizedDescription
}
}
func candidateSuggestions(for service: ServiceOccurrence, role: Role) -> [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] = [:]
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
}
let assignedToService = Set(assignments.filter { $0.serviceID == service.id }.map(\.personID))
let weekday = DayMath.weekday(service.date)
return people
.filter { $0.active && $0.canFill(role) && !assignedToService.contains($0.id) }
.map { person in
var warnings: [String] = []
var blocked = false
if absences.contains(where: { $0.personID == person.id && $0.overlaps(service.date) }) {
warnings.append("abwesend")
blocked = true
}
if !person.preferredWeekdays.isEmpty && !person.preferredWeekdays.contains(weekday) {
warnings.append("Einsatztag passt nicht")
blocked = true
}
if person.maxPerMonth > 0, monthlyCounts["\(person.id)|\(monthKey)", default: 0] >= person.maxPerMonth {
warnings.append("Monatslimit")
blocked = true
}
if dayCounts["\(person.id)|\(service.dateKey)", default: 0] > 0 {
warnings.append("bereits an diesem Tag")
blocked = true
}
var score = 0.0
var preferred = false
if person.preferredChurchIDs.contains(service.churchID) {
score += 8
preferred = true
}
if !person.preferredChurchIDs.isEmpty && !person.preferredChurchIDs.contains(service.churchID) {
score -= 2
}
if person.preferredWeekdays.contains(weekday) {
score += 3
preferred = true
}
for preference in person.preferredServiceTitles where !preference.isEmpty {
if service.title.lowercased().contains(preference.lowercased()) {
score += 4
preferred = true
}
}
score -= Double(totalCounts[person.id, default: 0]) * 1.4
if absences.contains(where: { $0.personID == person.id && $0.overlaps(service.date) }) {
score -= 100
}
return CandidateSuggestion(
person: person,
score: score,
warnings: warnings,
blocked: blocked,
preferred: preferred,
totalAssignments: totalCounts[person.id, default: 0]
)
}
.sorted {
if $0.blocked != $1.blocked { return !$0.blocked }
if $0.score != $1.score { return $0.score > $1.score }
return $0.person.lastName < $1.person.lastName
}
}
func serviceWithAssignments(id: String) -> ServiceWithAssignments? {
for row in rows {
if let match = row.services.first(where: { $0.service.id == id }) { return match }
}
// The service may be outside the current range while its detail sheet is open.
guard let service = try? db.service(id: id), let church = churchByID[service.churchID] else { return nil }
let serviceAssignments = (try? db.assignments(serviceIDs: [id])) ?? []
return ServiceWithAssignments(service: service, church: church, assignments: serviceAssignments)
}
func nextOpenServices(limit: Int = 8) -> [ServiceWithAssignments] {
rows
.flatMap(\.services)
.filter { !$0.isFullyStaffed }
.sorted { $0.service.date < $1.service.date }
.prefix(limit)
.map { $0 }
}
// MARK: - Liturgical calendar
func syncLiturgy(years: [Int]? = nil) async {
guard !isSyncing else { return }
isSyncing = true
defer { isSyncing = false }
let targetYears = years ?? Array(Set(range.days.map { DayMath.year($0) })).sorted()
var updated = 0
var errors: [String] = []
let api = LiturgicalCalendarAPI()
for year in targetYears {
syncMessage = "Lade liturgischen Kalender \(year)…"
do {
let days = try await api.fetch(year: year)
try db.replaceLiturgicalYear(year, with: days)
updated += days.count
} catch {
errors.append("\(year): \(error.localizedDescription)")
}
}
if updated > 0 {
let now = Date()
lastSync = now
db.setSetting("lastLiturgicalSync", value: ISO8601DateFormatter().string(from: now))
ensureLiturgicalCoverage()
loadAll()
showToast("Liturgischer Kalender aktualisiert · \(updated) Tage.", kind: .success)
}
syncMessage = ""
if !errors.isEmpty {
alertTitle = errors.count == targetYears.count ? "Kalender nicht erreichbar" : "Kalender teilweise aktualisiert"
alertMessage = errors.joined(separator: "\n") + "\n\nDie vorhandenen Offline-Daten bleiben erhalten. Quelle: www.eucharistiefeier.de"
}
}
func syncIfNeeded() {
// Screenshot runs should stay deterministic and offline.
guard ProcessInfo.processInfo.environment["LP_SNAPSHOT"] == nil else { return }
guard db.setting("autoSyncLiturgy") == "1" else { return }
if let lastSync, Date().timeIntervalSince(lastSync) < 24 * 3600 { return }
Task { await syncLiturgy(years: [DayMath.year(range.start)]) }
}
static var sourceLabel: String { "Daten von www.eucharistiefeier.de" }
// MARK: - People
func savePerson(_ person: Person) {
do {
try db.upsert(person)
loadAll()
showToast("\(person.fullName) gespeichert.", kind: .success)
} catch {
alertTitle = "Person konnte nicht gespeichert werden"
alertMessage = error.localizedDescription
}
}
func deletePerson(_ person: Person) {
do {
try db.deletePerson(id: person.id)
loadAll()
showToast("\(person.fullName) gelöscht.", kind: .info)
} catch {
alertTitle = "Person konnte nicht gelöscht werden"
alertMessage = error.localizedDescription
}
}
func absences(for personID: String) -> [Absence] {
absences.filter { $0.personID == personID }.sorted { $0.start < $1.start }
}
func saveAbsence(_ absence: Absence) {
do {
try db.upsert(absence)
loadAll()
} catch {
alertTitle = "Abwesenheit konnte nicht gespeichert werden"
alertMessage = error.localizedDescription
}
}
func deleteAbsence(_ absence: Absence) {
do {
try db.deleteAbsence(id: absence.id)
loadAll()
} catch {
alertTitle = "Abwesenheit konnte nicht gelöscht werden"
alertMessage = error.localizedDescription
}
}
func currentAbsence(for person: Person) -> Absence? {
let today = DayMath.today()
return absences.first { $0.personID == person.id && $0.range.contains(today) }
}
func assignmentCount(for personID: String) -> Int {
stats.personStats.first { $0.person.id == personID }?.total ?? 0
}
// MARK: - Service order
func templates(for churchID: String) -> [ServiceTemplate] {
templates.filter { $0.churchID == churchID }.sorted {
if $0.weekday != $1.weekday { return $0.weekday < $1.weekday }
return $0.timeMinutes < $1.timeMinutes
}
}
func saveTemplate(_ template: ServiceTemplate) {
do {
try db.upsert(template)
let created = try db.generateServices(in: range)
loadAll()
showToast("Gottesdienstordnung gespeichert. \(created) neue Termine erzeugt.", kind: .success)
} catch {
alertTitle = "Gottesdienstordnung konnte nicht gespeichert werden"
alertMessage = error.localizedDescription
}
}
func deleteTemplate(_ template: ServiceTemplate) {
do {
try db.deleteTemplate(id: template.id)
loadAll()
showToast("Vorlage gelöscht. Bereits erzeugte Termine bleiben erhalten.", kind: .info)
} catch {
alertTitle = "Vorlage konnte nicht gelöscht werden"
alertMessage = error.localizedDescription
}
}
func generateServices() {
do {
let created = try db.generateServices(in: range)
loadAll()
showToast(created > 0 ? "\(created) Gottesdienste erzeugt." : "Keine neuen Gottesdienste im Zeitraum.", kind: created > 0 ? .success : .info)
} catch {
alertTitle = "Gottesdienste konnten nicht erzeugt werden"
alertMessage = error.localizedDescription
}
}
func saveSpecialService(_ service: ServiceOccurrence) {
do {
try db.upsert(service)
loadAll()
showToast("Sondergottesdienst gespeichert.", kind: .success)
} catch {
alertTitle = "Sondergottesdienst konnte nicht gespeichert werden"
alertMessage = error.localizedDescription
}
}
func deleteService(_ service: ServiceOccurrence) {
do {
try db.deleteService(id: service.id)
loadAll()
serviceDetail = nil
showToast("Gottesdienst gelöscht.", kind: .info)
} catch {
alertTitle = "Gottesdienst konnte nicht gelöscht werden"
alertMessage = error.localizedDescription
}
}
var serviceTitles: [String] {
Array(Set(templates.map(\.title))).sorted()
}
func upcomingSpecials() -> [ServiceOccurrence] {
let cutoff = DayMath.adding(days: -31, to: DayMath.today())
return specialServices
.filter { $0.date >= cutoff }
.sorted { $0.date < $1.date }
}
// MARK: - Exchange
func exportData(scope: ExchangeScope) throws -> (data: Data, filename: String) {
let exchange = try db.exportPlan(range: range, scope: scope)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
encoder.dateEncodingStrategy = .iso8601
let data = try encoder.encode(exchange)
let suffix: String
if scope == .resources {
suffix = "Ressourcen_\(DayMath.key(DayMath.today()))"
} else {
suffix = "Plan_\(DayMath.key(range.start))_\(DayMath.key(range.end))"
}
return (data, "LektorenPlan_\(suffix).json")
}
func exportInteractive(scope: ExchangeScope) {
do {
let result = try exportData(scope: scope)
let panel = NSSavePanel()
panel.title = scope == .resources ? "Ressourcen exportieren" : "Planungsabschnitt exportieren"
panel.nameFieldStringValue = result.filename
panel.allowedContentTypes = [.json]
panel.canCreateDirectories = true
if panel.runModal() == .OK, let url = panel.url {
try result.data.write(to: url, options: .atomic)
showToast("Export gespeichert: \(url.lastPathComponent)", kind: .success)
}
} catch {
alertTitle = "Export fehlgeschlagen"
alertMessage = error.localizedDescription
}
}
func importInteractive() {
let panel = NSOpenPanel()
panel.title = "LektorenPlan-Datei importieren"
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.allowedContentTypes = [.json]
if panel.runModal() == .OK, let url = panel.url {
prepareImport(url: url)
}
}
func prepareImport(url: URL) {
do {
let accessing = url.startAccessingSecurityScopedResource()
defer { if accessing { url.stopAccessingSecurityScopedResource() } }
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
if let exchange = try? decoder.decode(PlanExchange.self, from: data) {
importPreview = ImportPreview(exchange: exchange, data: data, sourceName: url.lastPathComponent)
return
}
if let resources = try? decoder.decode(ResourceBundle.self, from: data) {
let exchange = PlanExchange(scope: .resources, range: range, resources: resources)
importPreview = ImportPreview(exchange: exchange, data: data, sourceName: url.lastPathComponent)
return
}
alertTitle = "Datei nicht erkannt"
alertMessage = "Die Datei enthält kein gültiges LektorenPlan-Austauschformat."
} catch {
alertTitle = "Import fehlgeschlagen"
alertMessage = error.localizedDescription
}
}
func applyImport(_ preview: ImportPreview) {
do {
let summary = try db.applyPlanExchange(preview.exchange)
importPreview = nil
loadAll()
showToast("Import abgeschlossen: \(summary.services) Gottesdienste, \(summary.assignments) Einsätze, \(summary.people) Personen.", kind: .success)
} catch {
alertTitle = "Import fehlgeschlagen"
alertMessage = error.localizedDescription
}
}
// MARK: - PDF & print
func createPDFPreview() {
let data = PlanPDFRenderer.render(
range: range,
rows: rows,
churches: churches,
people: peopleByID,
generatedAt: Date()
)
pdfPreview = PDFPreview(
data: data,
title: "Lektorenplan \(range.shortTitle)",
filename: "LektorenPlan_\(DayMath.key(range.start))_\(DayMath.key(range.end)).pdf"
)
}
func savePDF(data: Data, suggestedName: String) {
let panel = NSSavePanel()
panel.title = "PDF sichern"
panel.nameFieldStringValue = suggestedName
panel.allowedContentTypes = [.pdf]
if panel.runModal() == .OK, let url = panel.url {
do {
try data.write(to: url, options: .atomic)
showToast("PDF gespeichert: \(url.lastPathComponent)", kind: .success)
} catch {
alertTitle = "PDF konnte nicht gespeichert werden"
alertMessage = error.localizedDescription
}
}
}
func printPDF(data: Data? = nil) {
let pdfData = data ?? PlanPDFRenderer.render(
range: range,
rows: rows,
churches: churches,
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
info.topMargin = 0
info.bottomMargin = 0
info.leftMargin = 0
info.rightMargin = 0
if let operation = document.printOperation(for: info, scalingMode: .pageScaleToFit, autoRotate: true) {
operation.showsPrintPanel = true
operation.showsProgressPanel = true
operation.run()
}
}
// 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
}
}
func openDatabaseFolder() {
guard db.path != ":memory:" else { return }
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: db.path)])
}
var databaseSizeLabel: String {
let bytes = db.databaseSizeBytes()
return ByteCountFormatter.string(fromByteCount: Int64(bytes), countStyle: .file)
}
// MARK: - Toast
func showToast(_ message: String, kind: ToastKind = .info) {
toastTask?.cancel()
let newToast = Toast(message: message, kind: kind)
withAnimation(.spring(response: 0.32, dampingFraction: 0.86)) {
toast = newToast
}
toastTask = Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: 3_400_000_000)
guard !Task.isCancelled else { return }
guard self?.toast?.id == newToast.id else { return }
withAnimation(.easeOut(duration: 0.2)) {
self?.toast = nil
}
}
}
}
+236
View File
@@ -0,0 +1,236 @@
import SwiftUI
import LektorenPlanCore
struct RootView: View {
@EnvironmentObject private var model: PlanModel
var body: some View {
ZStack(alignment: .bottom) {
AppBackground()
NavigationSplitView {
SidebarView()
.navigationSplitViewColumnWidth(min: 214, ideal: 228, max: 252)
} detail: {
detail
}
.navigationSplitViewStyle(.balanced)
if let toast = model.toast {
ToastView(toast: toast)
.transition(.move(edge: .bottom).combined(with: .opacity))
.zIndex(50)
}
}
.frame(minWidth: 1120, minHeight: 740)
.task {
model.syncIfNeeded()
}
.alert(
model.alertTitle,
isPresented: Binding(
get: { model.alertMessage != nil },
set: { if !$0 { model.alertMessage = nil } }
)
) {
Button("OK", role: .cancel) { model.alertMessage = nil }
} message: {
Text(model.alertMessage ?? "")
}
.sheet(item: $model.personEditor) { request in
PersonEditorSheet(request: request)
.environmentObject(model)
}
.sheet(item: $model.templateEditor) { request in
TemplateEditorSheet(request: request)
.environmentObject(model)
}
.sheet(item: $model.specialServiceEditor) { request in
SpecialServiceSheet(request: request)
.environmentObject(model)
}
.sheet(item: $model.serviceDetail) { request in
ServiceDetailSheet(serviceID: request.serviceID)
.environmentObject(model)
}
.sheet(item: $model.importPreview) { preview in
ImportPreviewSheet(preview: preview)
.environmentObject(model)
}
.sheet(item: $model.pdfPreview) { preview in
PDFPreviewSheet(preview: preview)
.environmentObject(model)
}
.sheet(isPresented: Binding(
get: { model.planResult != nil },
set: { if !$0 { model.planResult = nil } }
)) {
PlanResultSheet()
.environmentObject(model)
}
}
@ViewBuilder
private var detail: some View {
switch model.section {
case .planning:
PlanningView()
.transition(.opacity)
case .serviceOrder:
ServiceOrderView()
.transition(.opacity)
case .team:
TeamView()
.transition(.opacity)
case .statistics:
StatisticsView()
.transition(.opacity)
case .exchange:
ExchangeView()
.transition(.opacity)
case .settings:
SettingsView()
.transition(.opacity)
}
}
}
private struct SidebarView: View {
@EnvironmentObject private var model: PlanModel
private var selection: Binding<AppSection?> {
Binding(
get: { model.section },
set: { value in
if let value { model.section = value }
}
)
}
var body: some View {
VStack(spacing: 0) {
branding
List(selection: selection) {
Section {
sidebarRow(.planning, badge: model.stats.openSlots > 0 ? "\(model.stats.openSlots)" : nil)
sidebarRow(.serviceOrder)
sidebarRow(.team, badge: "\(model.people.filter(\.active).count)")
sidebarRow(.statistics)
} header: {
sidebarHeader("Planung")
}
Section {
sidebarRow(.exchange)
sidebarRow(.settings)
} header: {
sidebarHeader("Organisation")
}
}
.listStyle(.sidebar)
.scrollContentBackground(.hidden)
.background(Color.clear)
footer
}
.background(
LinearGradient(colors: [LP.paper.opacity(0.72), LP.paperDeep.opacity(0.85)],
startPoint: .top, endPoint: .bottom)
)
}
private var branding: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 9) {
ZStack {
Circle()
.fill(LP.accent.opacity(0.09))
ChurchGlyph(symbol: .basilica, tint: LP.accent, lineWidth: 1.3, showGround: false)
.padding(5)
}
.frame(width: 38, height: 38)
.overlay(Circle().strokeBorder(LP.accent.opacity(0.18), lineWidth: 0.8))
VStack(alignment: .leading, spacing: 0) {
Text("LektorenPlan")
.font(.system(size: 18, weight: .semibold, design: .serif))
.foregroundStyle(LP.ink)
Text("Bad Godesberg")
.font(.system(size: 9, weight: .semibold, design: .rounded))
.tracking(0.8)
.foregroundStyle(LP.inkTertiary)
}
}
Text("GOTTESDIENSTE · DIENSTE · KALENDER")
.font(.system(size: 7.5, weight: .bold, design: .rounded))
.tracking(1.0)
.foregroundStyle(LP.inkTertiary.opacity(0.85))
}
.padding(.horizontal, 16)
.padding(.top, 38)
.padding(.bottom, 14)
}
private func sidebarHeader(_ title: String) -> some View {
Text(title.uppercased())
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(1.1)
.foregroundStyle(LP.inkTertiary)
}
private func sidebarRow(_ section: AppSection, badge: String? = nil) -> some View {
HStack(spacing: 9) {
Image(systemName: section.icon)
.font(.system(size: 12, weight: .medium))
.foregroundStyle(model.section == section ? LP.accent : LP.inkSecondary)
.frame(width: 18)
Text(section.title)
.font(.system(size: 12, weight: model.section == section ? .semibold : .regular))
.foregroundStyle(model.section == section ? LP.ink : LP.inkSecondary)
Spacer(minLength: 4)
if let badge {
Text(badge)
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.foregroundStyle(model.section == section ? LP.accent : LP.inkTertiary)
.padding(.horizontal, 5)
.padding(.vertical, 1.5)
.background(Capsule().fill(model.section == section ? LP.accent.opacity(0.12) : LP.cardMuted))
}
}
.tag(section)
.padding(.vertical, 2)
}
private var footer: some View {
VStack(alignment: .leading, spacing: 9) {
Hairline()
HStack(spacing: 6) {
Image(systemName: "calendar")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
Text(model.range.shortTitle)
.font(.system(size: 9.5, weight: .medium, design: .rounded))
.foregroundStyle(LP.inkSecondary)
.lineLimit(1)
}
HStack(spacing: 6) {
Circle()
.fill(model.lastSync == nil ? LP.open : LP.success)
.frame(width: 5, height: 5)
Text(model.lastSync == nil ? "Offline-Kalender aktiv" : "Kalender aktualisiert")
.font(.system(size: 8.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
Link(destination: URL(string: "https://www.eucharistiefeier.de")!) {
Text("Daten: www.eucharistiefeier.de")
.font(.system(size: 8, weight: .medium))
.foregroundStyle(LP.inkTertiary.opacity(0.85))
.underline()
}
Text("Prototyp 0.1 · Erzbistum Köln")
.font(.system(size: 7.5, weight: .regular))
.foregroundStyle(LP.inkTertiary.opacity(0.7))
}
.padding(.horizontal, 16)
.padding(.bottom, 14)
}
}
+123
View File
@@ -0,0 +1,123 @@
import SwiftUI
import AppKit
import LektorenPlanCore
/// Development helper: renders a view into a PNG (and optionally the plan PDF) so the
/// UI can be reviewed without screen-recording permissions.
/// Enabled only through the LP_SNAPSHOT / LP_PDF environment variables.
enum SnapshotCapture {
@MainActor
static func runIfRequested(model: PlanModel) async {
let environment = ProcessInfo.processInfo.environment
let wantsSnapshot = environment["LP_SNAPSHOT"] != nil
let wantsPDF = environment["LP_PDF"] != nil
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()
)
try? data.write(to: URL(fileURLWithPath: pdfPath))
}
guard wantsSnapshot, let path = snapshotPath else {
NSApplication.shared.terminate(nil)
return
}
let width = Double(environment["LP_SNAPSHOT_WIDTH"] ?? "") ?? 1440
let height = Double(environment["LP_SNAPSHOT_HEIGHT"] ?? "") ?? 869
let size = CGSize(width: width, height: height)
let content = SnapshotContent(view: environment["LP_SNAPSHOT_VIEW"])
.environmentObject(model)
.frame(width: size.width, height: size.height)
let hosting = NSHostingView(rootView: content)
hosting.frame = CGRect(origin: .zero, size: size)
let window = NSWindow(
contentRect: CGRect(origin: .zero, size: size),
styleMask: [.borderless],
backing: .buffered,
defer: false
)
window.contentView = hosting
window.orderFrontRegardless()
hosting.layoutSubtreeIfNeeded()
window.displayIfNeeded()
// Lazy containers and AppKit-backed controls need a run-loop cycle before capture.
try? await Task.sleep(nanoseconds: 800_000_000)
hosting.layoutSubtreeIfNeeded()
window.displayIfNeeded()
guard let rep = hosting.bitmapImageRepForCachingDisplay(in: hosting.bounds) else {
NSApplication.shared.terminate(nil)
return
}
hosting.cacheDisplay(in: hosting.bounds, to: rep)
if let png = rep.representation(using: .png, properties: [:]) {
try? png.write(to: URL(fileURLWithPath: path))
}
NSApplication.shared.terminate(nil)
}
private static var snapshotPath: String? {
ProcessInfo.processInfo.environment["LP_SNAPSHOT"]
}
}
private struct SnapshotContent: View {
@EnvironmentObject private var model: PlanModel
var view: String?
var body: some View {
switch view {
case "team":
screen { TeamView() }
case "order":
screen { ServiceOrderView() }
case "statistics":
screen { StatisticsView() }
case "exchange":
screen { ExchangeView() }
case "settings":
screen { SettingsView() }
case "person":
PersonEditorSheet(request: PersonEditorRequest(person: model.people.first))
case "detail":
if let serviceID = model.rows
.flatMap(\.services)
.first(where: { !$0.isFullyStaffed })?.service.id {
ServiceDetailSheet(serviceID: serviceID)
}
case "template":
if let template = model.templates.first {
TemplateEditorSheet(request: TemplateEditorRequest(template: template, churchID: template.churchID))
}
case "special":
SpecialServiceSheet(request: SpecialServiceRequest(
churchID: model.churches.first?.id,
date: DayMath.today()
))
case "root":
RootView()
default:
screen { PlanningView() }
}
}
@ViewBuilder
private func screen<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {
ZStack {
AppBackground()
content()
}
}
}
+581
View File
@@ -0,0 +1,581 @@
import SwiftUI
import AppKit
import LektorenPlanCore
enum LP {
static func dynamic(light: NSColor, dark: NSColor) -> Color {
Color(nsColor: NSColor(name: nil) { appearance in
appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? dark : light
})
}
static let paper = dynamic(
light: NSColor(calibratedRed: 0.973, green: 0.957, blue: 0.925, alpha: 1),
dark: NSColor(calibratedRed: 0.075, green: 0.078, blue: 0.086, alpha: 1)
)
static let paperDeep = dynamic(
light: NSColor(calibratedRed: 0.945, green: 0.924, blue: 0.882, alpha: 1),
dark: NSColor(calibratedRed: 0.055, green: 0.058, blue: 0.065, alpha: 1)
)
static let card = dynamic(
light: NSColor(calibratedWhite: 1.0, alpha: 1),
dark: NSColor(calibratedRed: 0.125, green: 0.129, blue: 0.141, alpha: 1)
)
static let cardMuted = dynamic(
light: NSColor(calibratedRed: 0.985, green: 0.975, blue: 0.955, alpha: 1),
dark: NSColor(calibratedRed: 0.155, green: 0.159, blue: 0.172, alpha: 1)
)
static let ink = dynamic(
light: NSColor(calibratedRed: 0.12, green: 0.135, blue: 0.155, alpha: 1),
dark: NSColor(calibratedRed: 0.93, green: 0.92, blue: 0.90, alpha: 1)
)
static let inkSecondary = dynamic(
light: NSColor(calibratedRed: 0.36, green: 0.37, blue: 0.38, alpha: 1),
dark: NSColor(calibratedRed: 0.68, green: 0.68, blue: 0.68, alpha: 1)
)
static let inkTertiary = dynamic(
light: NSColor(calibratedRed: 0.52, green: 0.51, blue: 0.49, alpha: 1),
dark: NSColor(calibratedRed: 0.48, green: 0.48, blue: 0.48, alpha: 1)
)
static let line = dynamic(
light: NSColor(calibratedRed: 0.86, green: 0.835, blue: 0.79, alpha: 1),
dark: NSColor(calibratedRed: 0.24, green: 0.245, blue: 0.26, alpha: 1)
)
static let accent = Color(hex: "#2E5B57")
static let accentSoft = dynamic(
light: NSColor(calibratedRed: 0.88, green: 0.925, blue: 0.905, alpha: 1),
dark: NSColor(calibratedRed: 0.13, green: 0.21, blue: 0.20, alpha: 1)
)
static let gold = Color(hex: "#B7863B")
static let goldSoft = dynamic(
light: NSColor(calibratedRed: 0.976, green: 0.925, blue: 0.80, alpha: 1),
dark: NSColor(calibratedRed: 0.24, green: 0.20, blue: 0.105, alpha: 1)
)
static let burgundy = Color(hex: "#7E3D4A")
static let burgundySoft = dynamic(
light: NSColor(calibratedRed: 0.966, green: 0.90, blue: 0.90, alpha: 1),
dark: NSColor(calibratedRed: 0.245, green: 0.13, blue: 0.15, alpha: 1)
)
static let sundayWash = dynamic(
light: NSColor(calibratedRed: 0.985, green: 0.955, blue: 0.885, alpha: 1),
dark: NSColor(calibratedRed: 0.18, green: 0.155, blue: 0.105, alpha: 1)
)
static let feastWash = dynamic(
light: NSColor(calibratedRed: 0.998, green: 0.955, blue: 0.79, alpha: 1),
dark: NSColor(calibratedRed: 0.23, green: 0.185, blue: 0.085, alpha: 1)
)
static let open = Color(hex: "#B26A22")
static let openSoft = dynamic(
light: NSColor(calibratedRed: 0.99, green: 0.93, blue: 0.84, alpha: 1),
dark: NSColor(calibratedRed: 0.24, green: 0.17, blue: 0.075, alpha: 1)
)
static let success = Color(hex: "#3F7A55")
static let successSoft = dynamic(
light: NSColor(calibratedRed: 0.89, green: 0.945, blue: 0.90, alpha: 1),
dark: NSColor(calibratedRed: 0.10, green: 0.22, blue: 0.14, alpha: 1)
)
static let danger = Color(hex: "#A5453F")
static let numberFont = Font.system(size: 13, weight: .semibold, design: .rounded)
static let labelFont = Font.system(size: 11, weight: .semibold, design: .rounded)
static let serifTitle = Font.system(size: 30, weight: .semibold, design: .serif)
static let serifHeadline = Font.system(size: 19, weight: .semibold, design: .serif)
static let serifSubhead = Font.system(size: 15, weight: .medium, design: .serif)
static func churchColor(_ hex: String) -> Color {
Color(hex: hex)
}
static func liturgicalColor(_ color: LiturgicalColor) -> Color {
switch color {
case .white, .gold: return Color(hex: "#C2A14D")
case .red: return Color(hex: "#A5453F")
case .green: return Color(hex: "#4F7D5A")
case .violet: return Color(hex: "#6E4B8E")
case .rose: return Color(hex: "#C07A8B")
case .black: return Color(hex: "#4A4440")
}
}
}
extension Color {
init(hex: String) {
let cleaned = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var value: UInt64 = 0
Scanner(string: cleaned).scanHexInt64(&value)
let r, g, b, a: UInt64
switch cleaned.count {
case 8:
r = (value >> 24) & 0xFF
g = (value >> 16) & 0xFF
b = (value >> 8) & 0xFF
a = value & 0xFF
case 6:
r = (value >> 16) & 0xFF
g = (value >> 8) & 0xFF
b = value & 0xFF
a = 255
default:
r = 120; g = 120; b = 120; a = 255
}
self.init(.sRGB, red: Double(r) / 255, green: Double(g) / 255, blue: Double(b) / 255, opacity: Double(a) / 255)
}
}
// MARK: - Surfaces
struct SurfaceCard<Content: View>: View {
var padding: CGFloat
var radius: CGFloat
var background: Color
var bordered: Bool
@ViewBuilder var content: Content
init(
padding: CGFloat = 18,
radius: CGFloat = 16,
background: Color = LP.card,
bordered: Bool = true,
@ViewBuilder content: () -> Content
) {
self.padding = padding
self.radius = radius
self.background = background
self.bordered = bordered
self.content = content()
}
var body: some View {
content
.padding(padding)
.background(
RoundedRectangle(cornerRadius: radius, style: .continuous)
.fill(background)
.shadow(color: .black.opacity(0.035), radius: 10, x: 0, y: 4)
)
.overlay(
RoundedRectangle(cornerRadius: radius, style: .continuous)
.strokeBorder(bordered ? LP.line.opacity(0.55) : .clear, lineWidth: 1)
)
}
}
struct AppBackground: View {
var body: some View {
ZStack {
LinearGradient(
colors: [LP.paper, LP.paperDeep, LP.paper],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
RadialGradient(
colors: [LP.gold.opacity(0.055), .clear],
center: .topTrailing,
startRadius: 20,
endRadius: 620
)
RadialGradient(
colors: [LP.accent.opacity(0.045), .clear],
center: .bottomLeading,
startRadius: 20,
endRadius: 700
)
}
.ignoresSafeArea()
}
}
// MARK: - Badges
struct TinyBadge: View {
var text: String
var color: Color
var filled: Bool = false
var body: some View {
Text(text)
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.tracking(0.4)
.foregroundStyle(filled ? Color.white : color)
.padding(.horizontal, 7)
.padding(.vertical, 3)
.background(
Capsule().fill(filled ? color : color.opacity(0.12))
)
.overlay(
Capsule().strokeBorder(filled ? .clear : color.opacity(0.20), lineWidth: 0.8)
)
}
}
struct RankBadge: View {
var day: LiturgicalDay
var body: some View {
if day.isHighFeast {
TinyBadge(text: "HOCHFEST", color: LP.gold, filled: true)
} else if day.rank == .feast {
TinyBadge(text: "FEST", color: LP.burgundy, filled: true)
} else if day.rank == .obligatoryMemorial {
TinyBadge(text: "GEDENKTAG", color: LP.accent)
} else if day.isObligation && !day.isSunday {
TinyBadge(text: "GEBOTEN", color: LP.burgundy)
}
}
}
struct RoleBadge: View {
var role: Role
var compact: Bool = false
var body: some View {
HStack(spacing: 4) {
Image(systemName: role.symbolName)
.font(.system(size: compact ? 8 : 9, weight: .semibold))
if !compact {
Text(role.title)
.font(.system(size: 9.5, weight: .semibold))
}
}
.foregroundStyle(role == .lector ? LP.accent : LP.burgundy)
.padding(.horizontal, compact ? 5 : 6)
.padding(.vertical, 2.5)
.background(
Capsule().fill(role == .lector ? LP.accent.opacity(0.09) : LP.burgundy.opacity(0.09))
)
}
}
struct Avatar: View {
var initials: String
var color: Color
var size: CGFloat = 26
var body: some View {
Text(initials)
.font(.system(size: size * 0.34, weight: .bold, design: .rounded))
.foregroundStyle(.white)
.frame(width: size, height: size)
.background(
Circle().fill(
LinearGradient(colors: [color.opacity(0.9), color.opacity(0.65)],
startPoint: .topLeading, endPoint: .bottomTrailing)
)
)
.overlay(Circle().strokeBorder(.white.opacity(0.28), lineWidth: 0.7))
}
}
struct PersonMiniChip: View {
var person: Person
var role: Role
var color: Color
var body: some View {
HStack(spacing: 4) {
Avatar(initials: person.initials, color: color, size: 18)
Text(person.firstNameWithInitial)
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
.lineLimit(1)
}
.padding(.horizontal, 4)
.padding(.vertical, 2)
.background(
Capsule().fill(LP.cardMuted)
)
.overlay(
Capsule().strokeBorder(LP.line.opacity(0.5), lineWidth: 0.6)
)
.help("\(person.fullName) · \(role.title)\n\(person.preferredChurchIDs.isEmpty ? "Alle Orte" : "Bevorzugte Orte") · max. \(person.maxPerMonth) Einsätze/Monat")
}
}
// MARK: - Buttons
struct PrimaryActionButton: View {
var title: String
var icon: String
var action: () -> Void
var disabled: Bool = false
var body: some View {
Button(action: action) {
HStack(spacing: 7) {
Image(systemName: icon)
.font(.system(size: 11, weight: .bold))
Text(title)
.font(.system(size: 12, weight: .semibold))
}
.foregroundStyle(.white)
.padding(.horizontal, 14)
.padding(.vertical, 8)
.background(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.fill(LinearGradient(colors: [LP.accent, LP.accent.opacity(0.82)],
startPoint: .top, endPoint: .bottom))
.shadow(color: LP.accent.opacity(0.20), radius: 5, y: 2)
)
}
.buttonStyle(.plain)
.disabled(disabled)
.opacity(disabled ? 0.45 : 1)
}
}
struct SecondaryActionButton: View {
var title: String
var icon: String
var action: () -> Void
var disabled: Bool = false
var tint: Color = LP.ink
var body: some View {
Button(action: action) {
HStack(spacing: 6) {
Image(systemName: icon)
.font(.system(size: 10.5, weight: .semibold))
Text(title)
.font(.system(size: 11.5, weight: .medium))
}
.foregroundStyle(tint)
.padding(.horizontal, 12)
.padding(.vertical, 7)
.background(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.fill(LP.card)
)
.overlay(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.strokeBorder(LP.line.opacity(0.8), lineWidth: 1)
)
}
.buttonStyle(.plain)
.disabled(disabled)
.opacity(disabled ? 0.45 : 1)
}
}
struct IconActionButton: View {
var icon: String
var help: String
var action: () -> Void
var tint: Color = LP.inkSecondary
var body: some View {
Button(action: action) {
Image(systemName: icon)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(tint)
.frame(width: 28, height: 28)
.background(Circle().fill(LP.card))
.overlay(Circle().strokeBorder(LP.line.opacity(0.7), lineWidth: 0.8))
}
.buttonStyle(.plain)
.help(help)
}
}
// MARK: - Headers
struct PageHeader<Trailing: View>: View {
var eyebrow: String
var title: String
var subtitle: String
@ViewBuilder var trailing: Trailing
init(eyebrow: String, title: String, subtitle: String, @ViewBuilder trailing: () -> Trailing) {
self.eyebrow = eyebrow
self.title = title
self.subtitle = subtitle
self.trailing = trailing()
}
var body: some View {
HStack(alignment: .bottom, spacing: 22) {
VStack(alignment: .leading, spacing: 5) {
Text(eyebrow.uppercased())
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.tracking(1.5)
.foregroundStyle(LP.accent)
Text(title)
.font(LP.serifTitle)
.foregroundStyle(LP.ink)
Text(subtitle)
.font(.system(size: 12, weight: .regular))
.foregroundStyle(LP.inkSecondary)
}
Spacer(minLength: 16)
trailing
}
}
}
extension PageHeader where Trailing == EmptyView {
init(eyebrow: String, title: String, subtitle: String) {
self.init(eyebrow: eyebrow, title: title, subtitle: subtitle) { EmptyView() }
}
}
struct SectionLabel: View {
var title: String
var trailing: String? = nil
var body: some View {
HStack(alignment: .firstTextBaseline) {
Text(title)
.font(.system(size: 10, weight: .bold, design: .rounded))
.tracking(1.3)
.foregroundStyle(LP.inkTertiary)
Spacer()
if let trailing {
Text(trailing)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
}
}
}
struct StatPill: View {
var icon: String
var value: String
var label: String
var tint: Color = LP.accent
var body: some View {
HStack(spacing: 9) {
Image(systemName: icon)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(tint)
.frame(width: 26, height: 26)
.background(Circle().fill(tint.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text(value)
.font(.system(size: 17, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
Text(label)
.font(.system(size: 9.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
}
}
}
struct EmptyStateView: View {
var icon: String
var title: String
var message: String
var actionTitle: String? = nil
var action: (() -> Void)? = nil
var body: some View {
VStack(spacing: 12) {
Image(systemName: icon)
.font(.system(size: 30, weight: .light))
.foregroundStyle(LP.inkTertiary)
Text(title)
.font(LP.serifHeadline)
.foregroundStyle(LP.ink)
Text(message)
.font(.system(size: 12))
.foregroundStyle(LP.inkSecondary)
.multilineTextAlignment(.center)
.frame(maxWidth: 360)
if let actionTitle, let action {
PrimaryActionButton(title: actionTitle, icon: "plus", action: action)
.padding(.top, 4)
}
}
.frame(maxWidth: .infinity)
.padding(.vertical, 44)
}
}
// MARK: - Toast
struct ToastView: View {
var toast: Toast
@Environment(\.colorScheme) private var scheme
var body: some View {
HStack(spacing: 10) {
Image(systemName: toast.kind.icon)
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(toast.kind.color)
Text(toast.message)
.font(.system(size: 12, weight: .medium))
.foregroundStyle(LP.ink)
.lineLimit(3)
}
.padding(.horizontal, 16)
.padding(.vertical, 11)
.background(
Capsule()
.fill(.regularMaterial)
.shadow(color: .black.opacity(0.16), radius: 16, y: 8)
)
.overlay(Capsule().strokeBorder(LP.line.opacity(0.6), lineWidth: 0.8))
.padding(.bottom, 24)
}
}
enum ToastKind {
case success, info, warning, error
var icon: String {
switch self {
case .success: "checkmark.circle.fill"
case .info: "info.circle.fill"
case .warning: "exclamationmark.triangle.fill"
case .error: "xmark.octagon.fill"
}
}
var color: Color {
switch self {
case .success: LP.success
case .info: LP.accent
case .warning: LP.open
case .error: LP.danger
}
}
}
struct Toast: Identifiable, Equatable {
var id = UUID()
var message: String
var kind: ToastKind
static func == (lhs: Toast, rhs: Toast) -> Bool { lhs.id == rhs.id }
}
// MARK: - Misc
struct Hairline: View {
var body: some View {
Rectangle().fill(LP.line.opacity(0.6)).frame(height: 1)
}
}
struct KeyboardShortcutHint: View {
var keys: String
var body: some View {
Text(keys)
.font(.system(size: 9, weight: .semibold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
.padding(.horizontal, 5)
.padding(.vertical, 2)
.background(RoundedRectangle(cornerRadius: 4).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(LP.line.opacity(0.7), lineWidth: 0.6))
}
}
struct FlowingSubhead: View {
var text: String
var body: some View {
Text(text)
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
}
@@ -0,0 +1,283 @@
import SwiftUI
import UniformTypeIdentifiers
import LektorenPlanCore
struct ExchangeView: View {
@EnvironmentObject private var model: PlanModel
@State private var isDropTarget = false
var body: some View {
VStack(spacing: 14) {
PageHeader(
eyebrow: "Austausch",
title: "Daten teilen & übernehmen",
subtitle: "Planungsabschnitte oder Ressourcen zwischen Installationen austauschen – als offenes JSON-Format."
) {
HStack(spacing: 8) {
SecondaryActionButton(title: "Importieren", icon: "square.and.arrow.down") {
model.importInteractive()
}
PrimaryActionButton(title: "Plan exportieren", icon: "square.and.arrow.up") {
model.exportInteractive(scope: .plan)
}
}
}
ScrollView {
VStack(alignment: .leading, spacing: 14) {
currentRangeBanner
HStack(alignment: .top, spacing: 14) {
exportPlanCard
exportResourcesCard
}
importCard
formatInfo
}
.padding(.bottom, 16)
}
}
.padding(.horizontal, 22)
.padding(.top, 30)
.padding(.bottom, 18)
}
private var currentRangeBanner: some View {
SurfaceCard(padding: 13, radius: 14, background: LP.card.opacity(0.9)) {
HStack(spacing: 12) {
Image(systemName: "calendar")
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(LP.accent)
.frame(width: 30, height: 30)
.background(Circle().fill(LP.accent.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text("Aktueller Planungsabschnitt")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
Text(model.range.title)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(LP.ink)
}
Spacer()
HStack(spacing: 14) {
countLabel("\(model.stats.serviceCount)", "Gottesdienste")
countLabel("\(model.stats.assignmentCount)", "Einsätze")
countLabel("\(model.stats.openSlots)", "offen")
}
SecondaryActionButton(title: "Zeitraum ändern", icon: "slider.horizontal.3") {
model.section = .planning
}
}
}
}
private func countLabel(_ value: String, _ label: String) -> some View {
VStack(alignment: .trailing, spacing: 0) {
Text(value)
.font(.system(size: 13, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
Text(label)
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
}
}
// MARK: - Export cards
private var exportPlanCard: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
cardHeader(
icon: "calendar.badge.clock",
title: "Planungsabschnitt",
subtitle: "Gottesdienste, Einsätze und Liturgie des aktuellen Zeitraums",
tint: LP.accent
)
VStack(alignment: .leading, spacing: 6) {
detailRow("Zeitraum", model.range.shortTitle)
detailRow("Gottesdienste", "\(model.stats.serviceCount)")
detailRow("Einsätze", "\(model.stats.assignmentCount)")
detailRow("Beteiligte Personen", "\(Set(model.assignments.map(\.personID)).count)")
detailRow("Liturgische Tage", "\(model.liturgicalDays.count)")
}
Text("Enthält zusätzlich die Stammdaten der beteiligten Personen sowie Kirchen, Vorlagen und Ausnahmen, damit der Abschnitt am Zielort vollständig lesbar ist.")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
PrimaryActionButton(title: "Plan als JSON exportieren", icon: "square.and.arrow.up") {
model.exportInteractive(scope: .plan)
}
}
}
}
private var exportResourcesCard: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
cardHeader(
icon: "person.2.badge.gearshape",
title: "Ressourcen",
subtitle: "Kirchen, Personen, Abwesenheiten und Gottesdienstordnung",
tint: LP.burgundy
)
VStack(alignment: .leading, spacing: 6) {
detailRow("Kirchen", "\(model.churches.count)")
detailRow("Personen", "\(model.people.count)")
detailRow("Abwesenheiten", "\(model.absences.count)")
detailRow("Vorlagen", "\(model.templates.count)")
detailRow("Ausnahmen", "\(model.exceptions.count)")
}
Text("Ideal zur Weitergabe des kompletten Stammdatenbestands an eine zweite Installation. Einsätze und Gottesdienste sind nicht enthalten.")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
PrimaryActionButton(title: "Ressourcen als JSON exportieren", icon: "square.and.arrow.up") {
model.exportInteractive(scope: .resources)
}
}
}
}
// MARK: - Import
private var importCard: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
cardHeader(
icon: "square.and.arrow.down",
title: "Datei importieren",
subtitle: "Zusammenführen mit dem aktuellen Bestand – ohne Datenverlust",
tint: LP.gold
)
HStack(spacing: 14) {
ZStack {
RoundedRectangle(cornerRadius: 12, style: .continuous)
.strokeBorder(
style: StrokeStyle(lineWidth: 1.2, dash: [5, 4])
)
.foregroundStyle(isDropTarget ? LP.accent : LP.line)
VStack(spacing: 6) {
Image(systemName: isDropTarget ? "arrow.down.doc.fill" : "doc.badge.plus")
.font(.system(size: 22, weight: .light))
.foregroundStyle(isDropTarget ? LP.accent : LP.inkTertiary)
Text(isDropTarget ? "Loslassen zum Prüfen" : "LektorenPlan-JSON hierher ziehen")
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.inkSecondary)
Text("oder Datei auswählen")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
}
.frame(height: 116)
.frame(maxWidth: .infinity)
.background(RoundedRectangle(cornerRadius: 12).fill(isDropTarget ? LP.accentSoft.opacity(0.4) : LP.cardMuted.opacity(0.35)))
.onDrop(of: [UTType.fileURL.identifier], isTargeted: $isDropTarget) { providers in
handleDrop(providers)
return true
}
VStack(alignment: .leading, spacing: 8) {
Text("Ablauf")
.font(.system(size: 9, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(LP.inkTertiary)
step(1, "Datei auswählen oder ablegen")
step(2, "Inhalt in der Vorschau prüfen")
step(3, "Zusammenführen bestätigen")
SecondaryActionButton(title: "Datei auswählen…", icon: "folder") {
model.importInteractive()
}
.padding(.top, 2)
}
.frame(width: 240, alignment: .leading)
}
}
}
}
private func step(_ number: Int, _ text: String) -> some View {
HStack(spacing: 7) {
Text("\(number)")
.font(.system(size: 8, weight: .bold, design: .rounded))
.foregroundStyle(LP.accent)
.frame(width: 16, height: 16)
.background(Circle().fill(LP.accent.opacity(0.10)))
Text(text)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
}
}
private func handleDrop(_ providers: [NSItemProvider]) {
guard let provider = providers.first else { return }
_ = provider.loadObject(ofClass: URL.self) { url, _ in
guard let url else { return }
Task { @MainActor in
model.prepareImport(url: url)
}
}
}
// MARK: - Info
private var formatInfo: some View {
SurfaceCard(padding: 15, radius: 14, background: LP.accentSoft.opacity(0.4)) {
HStack(alignment: .top, spacing: 10) {
Image(systemName: "info.circle")
.font(.system(size: 12))
.foregroundStyle(LP.accent)
VStack(alignment: .leading, spacing: 4) {
Text("Offenes Austauschformat")
.font(.system(size: 10.5, weight: .semibold))
.foregroundStyle(LP.ink)
Text("Die Dateien sind lesbare JSON-Dokumente mit Versionsnummer, Zeitraum, Ressourcen und Planungsdaten. Datensätze werden über stabile IDs zusammengeführt. Vor dem Import wird immer eine Vorschau mit allen enthaltenen Elementen angezeigt.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
Spacer()
}
}
}
private func cardHeader(icon: String, title: String, subtitle: String, tint: Color) -> some View {
HStack(alignment: .top, spacing: 9) {
Image(systemName: icon)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(tint)
.frame(width: 28, height: 28)
.background(Circle().fill(tint.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text(title)
.font(LP.serifSubhead)
.foregroundStyle(LP.ink)
Text(subtitle)
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
}
Spacer()
}
}
private func detailRow(_ label: String, _ value: String) -> some View {
HStack {
Text(label)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
Spacer()
Text(value)
.font(.system(size: 9.5, weight: .semibold, design: .rounded))
.foregroundStyle(LP.ink)
}
}
}
@@ -0,0 +1,125 @@
import SwiftUI
import LektorenPlanCore
struct ImportPreviewSheet: View {
@EnvironmentObject private var model: PlanModel
@Environment(\.dismiss) private var dismiss
let preview: ImportPreview
private var exchange: PlanExchange { preview.exchange }
private var summary: ExchangeSummary { exchange.summary }
var body: some View {
VStack(spacing: 0) {
SheetHeader(
icon: "square.and.arrow.down",
title: "Import prüfen",
subtitle: "Die Datei \(preview.sourceName) wurde gelesen. Prüfe den Inhalt, bevor du ihn übernimmst."
)
Hairline()
ScrollView {
VStack(alignment: .leading, spacing: 20) {
HStack(spacing: 10) {
TinyBadge(text: exchange.scope.title.uppercased(), color: LP.accent, filled: true)
Text("Format \(exchange.formatVersion) · \(exchange.appName)")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
Spacer()
if let exported = exchange.exportedAt as Date? {
Text("Exportiert am \(DayMath.mediumString(exported))")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
}
}
.padding(11)
.background(RoundedRectangle(cornerRadius: 9).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.8))
FormSection(title: "Zeitraum") {
HStack(spacing: 8) {
Image(systemName: "calendar")
.foregroundStyle(LP.accent)
Text(exchange.range.title)
.font(.system(size: 12, weight: .medium))
.foregroundStyle(LP.ink)
Text("· \(exchange.range.dayCount) Tage")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
}
}
FormSection(title: "Enthaltene Daten") {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 10)], spacing: 10) {
countCard(icon: "building.columns", value: summary.churches, label: "Kirchen", tint: LP.accent)
countCard(icon: "person.2", value: summary.people, label: "Personen", tint: LP.burgundy)
countCard(icon: "calendar.badge.clock", value: summary.templates, label: "Vorlagen", tint: LP.gold)
countCard(icon: "list.bullet.rectangle", value: summary.services, label: "Gottesdienste", tint: LP.accent)
countCard(icon: "checkmark.seal", value: summary.assignments, label: "Einsätze", tint: LP.success)
countCard(icon: "book.closed", value: summary.liturgicalDays, label: "Liturgische Tage", tint: LP.burgundy)
}
}
if !exchange.note.isEmpty {
FormSection(title: "Notiz") {
Text(exchange.note)
.font(.system(size: 10.5))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
}
HStack(alignment: .top, spacing: 8) {
Image(systemName: "info.circle")
.font(.system(size: 11))
.foregroundStyle(LP.accent)
Text("Datensätze werden anhand ihrer stabilen IDs zusammengeführt. Bereits vorhandene Kirchen, Personen und Vorlagen werden aktualisiert, neue Dienste und Einsätze ergänzt. Es wird nichts gelöscht.")
.font(.system(size: 10))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
.padding(11)
.background(RoundedRectangle(cornerRadius: 9).fill(LP.accentSoft.opacity(0.55)))
}
.padding(22)
}
SheetFooter {
Spacer()
SecondaryActionButton(title: "Abbrechen", icon: "xmark") {
model.importPreview = nil
dismiss()
}
PrimaryActionButton(title: "Importieren", icon: "square.and.arrow.down") {
model.applyImport(preview)
dismiss()
}
}
}
.sheetSurface(width: 620, height: 620)
}
private func countCard(icon: String, value: Int, label: String, tint: Color) -> some View {
HStack(spacing: 9) {
Image(systemName: icon)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(tint)
.frame(width: 28, height: 28)
.background(Circle().fill(tint.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text("\(value)")
.font(.system(size: 15, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
Text(label)
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
Spacer(minLength: 0)
}
.padding(9)
.background(RoundedRectangle(cornerRadius: 9).fill(LP.card))
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.8))
}
}
@@ -0,0 +1,83 @@
import SwiftUI
import PDFKit
import LektorenPlanCore
struct PDFPreviewSheet: View {
@EnvironmentObject private var model: PlanModel
@Environment(\.dismiss) private var dismiss
let preview: PDFPreview
private var document: PDFDocument? {
PDFDocument(data: preview.data)
}
var body: some View {
VStack(spacing: 0) {
HStack(spacing: 12) {
ZStack {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(LP.accent.opacity(0.11))
Image(systemName: "doc.richtext")
.font(.system(size: 16, weight: .semibold))
.foregroundStyle(LP.accent)
}
.frame(width: 38, height: 38)
VStack(alignment: .leading, spacing: 2) {
Text(preview.title)
.font(LP.serifHeadline)
.foregroundStyle(LP.ink)
Text("\(document?.pageCount ?? 0) Seiten · A4 quer · bereit zum Drucken")
.font(.system(size: 10))
.foregroundStyle(LP.inkSecondary)
}
Spacer()
SecondaryActionButton(title: "Sichern", icon: "square.and.arrow.down") {
model.savePDF(data: preview.data, suggestedName: preview.filename)
}
SecondaryActionButton(title: "Drucken", icon: "printer") {
model.printPDF(data: preview.data)
}
PrimaryActionButton(title: "Fertig", icon: "checkmark") { dismiss() }
}
.padding(.horizontal, 20)
.padding(.vertical, 14)
Hairline()
if let document {
PDFKitPreview(document: document)
.background(Color(nsColor: .windowBackgroundColor))
} else {
EmptyStateView(
icon: "exclamationmark.triangle",
title: "PDF nicht verfügbar",
message: "Das Dokument konnte nicht erzeugt werden."
)
}
}
.sheetSurface(width: 960, height: 760)
}
}
private struct PDFKitPreview: NSViewRepresentable {
let document: PDFDocument
func makeNSView(context: Context) -> PDFView {
let view = PDFView()
view.document = document
view.autoScales = true
view.displayMode = .singlePageContinuous
view.displayDirection = .vertical
view.backgroundColor = NSColor(calibratedWhite: 0.90, alpha: 1)
view.pageShadowsEnabled = true
return view
}
func updateNSView(_ nsView: PDFView, context: Context) {
if nsView.document !== document {
nsView.document = document
}
}
}
@@ -0,0 +1,452 @@
import SwiftUI
import LektorenPlanCore
struct PersonEditorSheet: View {
@EnvironmentObject private var model: PlanModel
@Environment(\.dismiss) private var dismiss
let request: PersonEditorRequest
@State private var firstName = ""
@State private var lastName = ""
@State private var email = ""
@State private var phone = ""
@State private var roles: Set<Role> = [.lector]
@State private var preferredChurchIDs: Set<String> = []
@State private var preferredWeekdays: Set<Int> = []
@State private var preferredServiceTitles: Set<String> = []
@State private var maxPerMonth = 6
@State private var active = true
@State private var notes = ""
@State private var showAbsenceForm = false
@State private var absenceStart = DayMath.today()
@State private var absenceEnd = DayMath.today()
@State private var absenceReason = ""
@State private var confirmDelete = false
private var personID: String? { request.person?.id }
private var weekdayOrder: [Int] { [2, 3, 4, 5, 6, 7, 1] }
private func weekdayLabel(_ weekday: Int) -> String {
["", "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"][max(0, min(7, weekday))]
}
private var isValid: Bool {
!firstName.trimmingCharacters(in: .whitespaces).isEmpty
&& !lastName.trimmingCharacters(in: .whitespaces).isEmpty
&& !roles.isEmpty
}
var body: some View {
VStack(spacing: 0) {
SheetHeader(
icon: request.person == nil ? "person.badge.plus" : "person.crop.circle",
title: request.person == nil ? "Neue Person" : request.person?.fullName ?? "Person",
subtitle: "Rollen, bevorzugte Einsatzorte und Einsatztage, Abwesenheiten und Monatslimit."
)
Hairline()
ScrollView {
VStack(alignment: .leading, spacing: 22) {
basics
rolesSection
preferencesSection
capacitySection
if let personID, let person = request.person {
absenceSection(person: person, personID: personID)
}
}
.padding(22)
}
SheetFooter {
if request.person != nil {
Button {
confirmDelete = true
} label: {
HStack(spacing: 5) {
Image(systemName: "trash")
Text("Löschen")
}
.font(.system(size: 11.5, weight: .medium))
.foregroundStyle(LP.danger)
}
.buttonStyle(.plain)
}
Spacer()
SecondaryActionButton(title: "Abbrechen", icon: "xmark") { dismiss() }
PrimaryActionButton(
title: "Speichern",
icon: "checkmark",
action: save,
disabled: !isValid
)
}
}
.sheetSurface(width: 640, height: 700)
.onAppear(perform: load)
.confirmationDialog(
"Person löschen?",
isPresented: $confirmDelete,
titleVisibility: .visible
) {
Button("Endgültig löschen", role: .destructive) {
if let person = request.person {
model.deletePerson(person)
}
dismiss()
}
Button("Abbrechen", role: .cancel) {}
} message: {
Text("Alle Einsätze und Abwesenheiten dieser Person werden mit entfernt. Bereits geplante Dienste werden wieder offen.")
}
}
// MARK: - Sections
private var basics: some View {
FormSection(title: "Stammdaten") {
HStack(spacing: 12) {
LabeledField(label: "Vorname") {
TextField("z. B. Anna", text: $firstName)
.textFieldStyle(.roundedBorder)
}
LabeledField(label: "Nachname") {
TextField("z. B. Berg", text: $lastName)
.textFieldStyle(.roundedBorder)
}
}
HStack(spacing: 12) {
LabeledField(label: "E-Mail") {
TextField("optional", text: $email)
.textFieldStyle(.roundedBorder)
}
LabeledField(label: "Telefon") {
TextField("optional", text: $phone)
.textFieldStyle(.roundedBorder)
}
}
}
}
private var rolesSection: some View {
FormSection(
title: "Rollen",
subtitle: "Eine Person kann als Lektor und als Kommunionhelfer eingeplant werden."
) {
HStack(spacing: 8) {
ForEach(Role.allCases) { role in
ChipToggle(
title: role.titlePluralShort,
icon: role.symbolName,
isOn: roles.contains(role),
tint: role == .lector ? LP.accent : LP.burgundy
) {
if roles.contains(role) {
if roles.count > 1 { roles.remove(role) }
} else {
roles.insert(role)
}
}
}
Spacer()
Toggle(isOn: $active) {
Text("Aktiv im Plan")
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.inkSecondary)
}
.toggleStyle(.switch)
.controlSize(.small)
}
}
}
private var preferencesSection: some View {
FormSection(
title: "Einsatzpräferenzen",
subtitle: "Leere Auswahl bedeutet: flexibel für alle Orte, Tage und Gottesdienste."
) {
VStack(alignment: .leading, spacing: 5) {
Text("Bevorzugte Kirchen")
.font(.system(size: 9.5, weight: .semibold))
.foregroundStyle(LP.inkSecondary)
FlowLayout(spacing: 6) {
ForEach(model.churches) { church in
ChipToggle(
title: church.shortName,
icon: "building.columns",
isOn: preferredChurchIDs.contains(church.id),
tint: LP.churchColor(church.colorHex)
) {
if preferredChurchIDs.contains(church.id) {
preferredChurchIDs.remove(church.id)
} else {
preferredChurchIDs.insert(church.id)
}
}
}
}
}
VStack(alignment: .leading, spacing: 5) {
Text("Bevorzugte Einsatztage")
.font(.system(size: 9.5, weight: .semibold))
.foregroundStyle(LP.inkSecondary)
HStack(spacing: 5) {
ForEach(weekdayOrder, id: \.self) { weekday in
ChipToggle(
title: weekdayLabel(weekday),
isOn: preferredWeekdays.contains(weekday),
tint: weekday == 1 ? LP.burgundy : LP.accent
) {
if preferredWeekdays.contains(weekday) {
preferredWeekdays.remove(weekday)
} else {
preferredWeekdays.insert(weekday)
}
}
}
}
}
VStack(alignment: .leading, spacing: 5) {
Text("Bevorzugte Gottesdienste")
.font(.system(size: 9.5, weight: .semibold))
.foregroundStyle(LP.inkSecondary)
FlowLayout(spacing: 6) {
ForEach(model.serviceTitles, id: \.self) { title in
ChipToggle(
title: title,
icon: "book.closed",
isOn: preferredServiceTitles.contains(title),
tint: LP.gold
) {
if preferredServiceTitles.contains(title) {
preferredServiceTitles.remove(title)
} else {
preferredServiceTitles.insert(title)
}
}
}
}
}
}
}
private var capacitySection: some View {
FormSection(title: "Kapazität & Notizen") {
HStack(spacing: 16) {
LabeledField(label: "Maximale Einsätze pro Monat") {
HStack(spacing: 8) {
Stepper(value: $maxPerMonth, in: 1...30) {
Text("\(maxPerMonth)")
.font(.system(size: 12, weight: .semibold, design: .rounded))
.monospacedDigit()
}
.fixedSize()
Text(maxPerMonth >= 12 ? "sehr flexibel" : "Einsätze")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
}
}
Spacer()
}
LabeledField(label: "Notizen") {
TextEditor(text: $notes)
.font(.system(size: 11))
.frame(height: 62)
.padding(5)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.card))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.8), lineWidth: 1))
}
}
}
private func absenceSection(person: Person, personID: String) -> some View {
FormSection(
title: "Abwesenheiten",
subtitle: "In diesen Zeiträumen wird die Person nicht eingeplant."
) {
let list = model.absences(for: personID)
if list.isEmpty {
Text("Keine Abwesenheiten erfasst.")
.font(.system(size: 10.5))
.foregroundStyle(LP.inkTertiary)
} else {
VStack(spacing: 5) {
ForEach(list) { absence in
HStack(spacing: 8) {
Image(systemName: "calendar.badge.minus")
.font(.system(size: 10))
.foregroundStyle(LP.open)
Text(absence.label)
.font(.system(size: 10.5))
.foregroundStyle(LP.ink)
Spacer()
Button {
model.deleteAbsence(absence)
} label: {
Image(systemName: "xmark.circle.fill")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
}
.buttonStyle(.plain)
.help("Abwesenheit entfernen")
}
.padding(.horizontal, 9)
.padding(.vertical, 6)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.card))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.8))
}
}
}
if showAbsenceForm {
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 10) {
DatePicker("Von", selection: $absenceStart, displayedComponents: .date)
.font(.system(size: 10.5))
DatePicker("Bis", selection: $absenceEnd, displayedComponents: .date)
.font(.system(size: 10.5))
}
HStack(spacing: 8) {
TextField("Grund (optional)", text: $absenceReason)
.textFieldStyle(.roundedBorder)
.font(.system(size: 11))
PrimaryActionButton(title: "Hinzufügen", icon: "plus", action: addAbsence)
}
}
.padding(10)
.background(RoundedRectangle(cornerRadius: 9).fill(LP.cardMuted))
}
Button {
withAnimation(.easeInOut(duration: 0.16)) {
showAbsenceForm.toggle()
}
} label: {
HStack(spacing: 4) {
Image(systemName: showAbsenceForm ? "minus.circle" : "plus.circle")
Text(showAbsenceForm ? "Eingabe schließen" : "Abwesenheit erfassen")
}
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.accent)
}
.buttonStyle(.plain)
}
}
// MARK: - Actions
private func load() {
guard let person = request.person else {
if let role = request.presetRole {
roles = [role]
}
return
}
firstName = person.firstName
lastName = person.lastName
email = person.email
phone = person.phone
roles = person.roles
preferredChurchIDs = person.preferredChurchIDs
preferredWeekdays = person.preferredWeekdays
preferredServiceTitles = Set(person.preferredServiceTitles)
maxPerMonth = person.maxPerMonth
active = person.active
notes = person.notes
}
private func addAbsence() {
guard let personID else { return }
let start = min(absenceStart, absenceEnd)
let end = max(absenceStart, absenceEnd)
model.saveAbsence(Absence(
personID: personID,
start: start,
end: end,
reason: absenceReason.trimmingCharacters(in: .whitespaces)
))
absenceReason = ""
showAbsenceForm = false
}
private func save() {
let person = Person(
id: personID ?? UUID().uuidString,
firstName: firstName.trimmingCharacters(in: .whitespaces),
lastName: lastName.trimmingCharacters(in: .whitespaces),
roles: roles,
email: email.trimmingCharacters(in: .whitespaces),
phone: phone.trimmingCharacters(in: .whitespaces),
preferredChurchIDs: preferredChurchIDs,
preferredWeekdays: preferredWeekdays,
preferredServiceTitles: Array(preferredServiceTitles).sorted(),
maxPerMonth: maxPerMonth,
active: active,
notes: notes.trimmingCharacters(in: .whitespacesAndNewlines)
)
model.savePerson(person)
dismiss()
}
}
private extension Role {
var titlePluralShort: String {
switch self {
case .lector: "Lektor"
case .helper: "Kommunionhelfer"
}
}
}
// MARK: - Flow layout
/// A tiny wrapping layout so preference chips flow naturally in narrow sheets.
struct FlowLayout: Layout {
var spacing: CGFloat = 6
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let maxWidth = proposal.width ?? .infinity
var x: CGFloat = 0
var y: CGFloat = 0
var rowHeight: CGFloat = 0
var usedWidth: CGFloat = 0
for subview in subviews {
let size = subview.sizeThatFits(.unspecified)
if x > 0, x + size.width > maxWidth {
x = 0
y += rowHeight + spacing
rowHeight = 0
}
x += size.width + spacing
usedWidth = max(usedWidth, x - spacing)
rowHeight = max(rowHeight, size.height)
}
return CGSize(width: min(usedWidth, maxWidth == .infinity ? usedWidth : maxWidth),
height: y + rowHeight)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
var x = bounds.minX
var y = bounds.minY
var rowHeight: CGFloat = 0
for subview in subviews {
let size = subview.sizeThatFits(.unspecified)
if x > bounds.minX, x + size.width > bounds.maxX {
x = bounds.minX
y += rowHeight + spacing
rowHeight = 0
}
subview.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size))
x += size.width + spacing
rowHeight = max(rowHeight, size.height)
}
}
}
@@ -0,0 +1,143 @@
import SwiftUI
import LektorenPlanCore
struct PlanResultSheet: View {
@EnvironmentObject private var model: PlanModel
@Environment(\.dismiss) private var dismiss
var body: some View {
VStack(spacing: 0) {
if let result = model.planResult {
SheetHeader(
icon: result.unfilled.isEmpty ? "checkmark.seal" : "exclamationmark.triangle",
title: result.unfilled.isEmpty ? "Planung abgeschlossen" : "Planung mit Lücken",
subtitle: result.message,
tint: result.unfilled.isEmpty ? LP.success : LP.open
)
Hairline()
ScrollView {
VStack(alignment: .leading, spacing: 18) {
HStack(spacing: 12) {
resultTile(
icon: "checkmark.circle",
value: "\(result.filledCount)",
label: "neu besetzte Dienste",
tint: LP.success
)
resultTile(
icon: "circle.dashed",
value: "\(result.unfilled.count)",
label: "offene Dienste",
tint: LP.open
)
resultTile(
icon: "person.2",
value: "\(model.stats.assignmentCount)",
label: "Einsätze im Zeitraum",
tint: LP.accent
)
}
if result.unfilled.isEmpty {
HStack(alignment: .top, spacing: 9) {
Image(systemName: "sparkles")
.foregroundStyle(LP.gold)
Text("Alle Dienste im gewählten Zeitraum konnten unter Berücksichtigung von Abwesenheiten, Einsatztagen und Monatslimits besetzt werden. Gesperrte Einsätze wurden nicht verändert.")
.font(.system(size: 10.5))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
.padding(12)
.background(RoundedRectangle(cornerRadius: 10).fill(LP.successSoft.opacity(0.6)))
} else {
FormSection(
title: "Nicht besetzbare Dienste",
subtitle: "Die genannten Gründe zeigen, warum keine geeignete Person gefunden wurde."
) {
VStack(spacing: 0) {
ForEach(Array(result.unfilled.enumerated()), id: \.element.id) { index, slot in
HStack(alignment: .top, spacing: 10) {
VStack(alignment: .leading, spacing: 1) {
Text(DayMath.shortWeekdayName(slot.service.date).uppercased())
.font(.system(size: 7.5, weight: .bold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
Text("\(DayMath.dayNumber(slot.service.date)).")
.font(.system(size: 14, weight: .semibold, design: .serif))
.foregroundStyle(LP.ink)
Text(DayMath.shortMonthName(slot.service.date))
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
}
.frame(width: 34)
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 5) {
Text(slot.service.timeLabel)
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.foregroundStyle(LP.accent)
Text(slot.service.title)
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
}
Text("\(slot.churchName) · \(slot.role.title)")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
Text(slot.reason)
.font(.system(size: 9.5))
.foregroundStyle(LP.open)
}
Spacer()
}
.padding(.horizontal, 10)
.padding(.vertical, 7)
.background(index % 2 == 0 ? LP.cardMuted.opacity(0.4) : Color.clear)
}
}
.clipShape(RoundedRectangle(cornerRadius: 9))
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(LP.line.opacity(0.55), lineWidth: 0.8))
}
}
}
.padding(22)
}
SheetFooter {
Spacer()
SecondaryActionButton(title: "Statistik ansehen", icon: "chart.xyaxis.line") {
model.planResult = nil
model.section = .statistics
dismiss()
}
PrimaryActionButton(title: "Schließen", icon: "checkmark") {
model.planResult = nil
dismiss()
}
}
} else {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.sheetSurface(width: 620, height: 560)
}
private func resultTile(icon: String, value: String, label: String, tint: Color) -> some View {
VStack(alignment: .leading, spacing: 4) {
Image(systemName: icon)
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(tint)
Text(value)
.font(.system(size: 22, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
Text(label)
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(12)
.background(RoundedRectangle(cornerRadius: 10).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(LP.line.opacity(0.55), lineWidth: 0.8))
}
}
@@ -0,0 +1,721 @@
import SwiftUI
import LektorenPlanCore
struct PlanningView: View {
@EnvironmentObject private var model: PlanModel
@State private var showReplanConfirm = false
@State private var showSyncHelp = false
var body: some View {
VStack(spacing: 14) {
header
kpiRow
TimelineRangePicker()
CalendarTable()
.frame(maxHeight: .infinity)
}
.padding(.horizontal, 22)
.padding(.top, 30)
.padding(.bottom, 18)
.confirmationDialog(
"Gesamten Zeitraum neu planen?",
isPresented: $showReplanConfirm,
titleVisibility: .visible
) {
Button("Neu planen", role: .destructive) {
_ = model.autoPlan(replaceExisting: true)
}
Button("Abbrechen", role: .cancel) {}
} message: {
Text("Nicht gesperrte Zuweisungen im Zeitraum werden verworfen und fair neu verteilt. Gesperrte Einsätze bleiben erhalten.")
}
}
private var header: some View {
PageHeader(
eyebrow: "Pfarreiengemeinschaft Bad Godesberg",
title: "Gottesdienste im Blick",
subtitle: "Lektoren, Kommunionhelfer und liturgischer Kalender · Erzbistum Köln"
) {
HStack(spacing: 8) {
if model.isSyncing {
HStack(spacing: 6) {
ProgressView().controlSize(.small)
Text(model.syncMessage.isEmpty ? "Kalender…" : model.syncMessage)
.font(.system(size: 10.5))
.foregroundStyle(LP.inkSecondary)
}
.padding(.horizontal, 10)
}
SecondaryActionButton(title: "Kalender", icon: "arrow.triangle.2.circlepath") {
Task { await model.syncLiturgy() }
}
.help("Liturgischen Kalender für \(rangeYearsLabel) von www.eucharistiefeier.de aktualisieren")
.disabled(model.isSyncing)
SecondaryActionButton(title: "PDF", icon: "doc.richtext") {
model.createPDFPreview()
}
.help("Planung als PDF ansehen, sichern oder drucken")
Menu {
Button {
_ = model.autoPlan(replaceExisting: false)
} label: {
Label("Offene Dienste besetzen", systemImage: "wand.and.stars")
}
Button {
showReplanConfirm = true
} label: {
Label("Zeitraum neu planen…", systemImage: "arrow.triangle.2.circlepath")
}
} label: {
HStack(spacing: 7) {
Image(systemName: "wand.and.stars")
.font(.system(size: 11, weight: .bold))
Text("Automatisch planen")
.font(.system(size: 12, weight: .semibold))
Image(systemName: "chevron.down")
.font(.system(size: 8, weight: .bold))
.opacity(0.7)
}
.foregroundStyle(.white)
.padding(.horizontal, 14)
.padding(.vertical, 8)
.background(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.fill(LinearGradient(colors: [LP.accent, LP.accent.opacity(0.82)],
startPoint: .top, endPoint: .bottom))
.shadow(color: LP.accent.opacity(0.20), radius: 5, y: 2)
)
}
.menuStyle(.borderlessButton)
.fixedSize()
.help("Alle offenen Dienste im Zeitraum automatisch besetzen")
}
}
}
private var rangeYearsLabel: String {
let years = Array(Set(model.range.days.map { DayMath.year($0) })).sorted()
return years.map(String.init).joined(separator: ", ")
}
private var kpiRow: some View {
SurfaceCard(padding: 14, radius: 14, background: LP.card.opacity(0.88)) {
HStack(spacing: 0) {
StatPill(icon: "building.columns", value: "\(model.stats.serviceCount)", label: "Gottesdienste")
divider
StatPill(icon: "checkmark.seal", value: "\(model.stats.assignmentCount)", label: "Einsätze", tint: LP.success)
divider
StatPill(icon: "person.crop.circle.badge.exclamationmark", value: "\(model.stats.openSlots)", label: "Offene Dienste", tint: LP.open)
divider
StatPill(icon: "person.2", value: "\(model.people.filter(\.active).count)", label: "Aktive Personen", tint: LP.burgundy)
divider
StatPill(icon: "cross.case", value: "\(model.stats.sundayServiceCount)", label: "Sonntagsgottesdienste", tint: LP.gold)
Spacer(minLength: 12)
VStack(alignment: .trailing, spacing: 4) {
Text("BESETZUNGSQUOTE")
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(1)
.foregroundStyle(LP.inkTertiary)
HStack(alignment: .firstTextBaseline, spacing: 4) {
Text("\(Int(model.stats.coverageRate * 100))")
.font(.system(size: 24, weight: .bold, design: .rounded))
.foregroundStyle(model.stats.openSlots == 0 ? LP.success : LP.ink)
Text("%")
.font(.system(size: 12, weight: .semibold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
}
ProgressView(value: model.stats.coverageRate)
.progressViewStyle(.linear)
.tint(model.stats.openSlots == 0 ? LP.success : LP.accent)
.frame(width: 100)
}
}
}
}
private var divider: some View {
Rectangle()
.fill(LP.line.opacity(0.55))
.frame(width: 1, height: 32)
.padding(.horizontal, 14)
}
}
// MARK: - Calendar table
private struct CalendarTable: View {
@EnvironmentObject private var model: PlanModel
private let gap: CGFloat = 8
private let horizontalPadding: CGFloat = 12
private let dateWidth: CGFloat = 86
private let liturgyWidth: CGFloat = 240
private let churchMinWidth: CGFloat = 186
var body: some View {
SurfaceCard(padding: 0, radius: 16, background: LP.card) {
VStack(spacing: 0) {
toolbar
Hairline()
GeometryReader { geo in
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
)
}
}
}
.padding(.bottom, 10)
}
}
}
.frame(width: width, height: geo.size.height, alignment: .top)
}
}
}
}
}
private var toolbar: some View {
HStack(spacing: 12) {
HStack(spacing: 2) {
ForEach(PlanFilter.allCases) { filter in
Button {
withAnimation(.easeInOut(duration: 0.18)) {
model.filter = filter
}
} label: {
HStack(spacing: 4) {
Text(filter.title)
.font(.system(size: 10.5, weight: .semibold))
if filter == .open, model.stats.openSlots > 0 {
Text("\(model.stats.openSlots)")
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.foregroundStyle(.white)
.padding(.horizontal, 4)
.padding(.vertical, 1)
.background(Capsule().fill(LP.open))
}
}
.foregroundStyle(model.filter == filter ? Color.white : LP.inkSecondary)
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(
Capsule().fill(model.filter == filter ? LP.accent : Color.clear)
)
}
.buttonStyle(.plain)
}
}
.padding(3)
.background(Capsule().fill(LP.cardMuted))
.overlay(Capsule().strokeBorder(LP.line.opacity(0.55), lineWidth: 0.7))
Toggle(isOn: Binding(
get: { model.showOnlySundaysAndFeasts },
set: { model.setSundayFilter($0) }
)) {
Text("Sonn- & Feiertage")
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.inkSecondary)
}
.toggleStyle(.checkbox)
searchField
Spacer(minLength: 8)
legend
Text("\(model.filteredRows.count) Tage")
.font(.system(size: 9.5, weight: .medium, design: .rounded))
.foregroundStyle(LP.inkTertiary)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Capsule().fill(LP.cardMuted))
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
}
private var searchField: some View {
HStack(spacing: 5) {
Image(systemName: "magnifyingglass")
.font(.system(size: 10, weight: .medium))
.foregroundStyle(LP.inkTertiary)
TextField("Person, Ort, Lesung…", text: $model.searchText)
.textFieldStyle(.plain)
.font(.system(size: 10.5))
.frame(width: 150)
if !model.searchText.isEmpty {
Button {
model.searchText = ""
} label: {
Image(systemName: "xmark.circle.fill")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
.buttonStyle(.plain)
}
}
.padding(.horizontal, 8)
.padding(.vertical, 5)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.7))
}
private var legend: some View {
HStack(spacing: 9) {
legendItem(color: LP.sundayWash, text: "Sonntag")
legendItem(color: LP.feastWash, text: "Hochfest")
HStack(spacing: 3) {
Image(systemName: "circle.dashed")
.font(.system(size: 8))
.foregroundStyle(LP.open)
Text("offen")
}
.font(.system(size: 8.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
}
private func legendItem(color: Color, text: String) -> some View {
HStack(spacing: 3) {
RoundedRectangle(cornerRadius: 2).fill(color).frame(width: 8, height: 8)
.overlay(RoundedRectangle(cornerRadius: 2).strokeBorder(LP.line.opacity(0.5), lineWidth: 0.5))
Text(text)
}
.font(.system(size: 8.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
private func columnHeader(churchWidth: CGFloat) -> some View {
HStack(spacing: gap) {
Text("TAG")
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(1.1)
.foregroundStyle(LP.inkTertiary)
.frame(width: dateWidth, alignment: .leading)
Text("LITURGIE & LESUNGEN")
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(1.1)
.foregroundStyle(LP.inkTertiary)
.frame(width: liturgyWidth, alignment: .leading)
ForEach(model.churches) { church in
ChurchColumnHeader(church: church, width: churchWidth)
}
}
.padding(.horizontal, horizontalPadding)
.padding(.vertical, 10)
.background(LP.cardMuted.opacity(0.55))
}
private func monthHeader(_ group: MonthGroup, churchWidth: CGFloat) -> some View {
HStack(spacing: 8) {
Text(group.title.uppercased())
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.tracking(1.1)
.foregroundStyle(LP.inkSecondary)
Hairline()
Text("\(group.serviceCount) Gottesdienste")
.font(.system(size: 8.5, weight: .medium, design: .rounded))
.foregroundStyle(LP.inkTertiary)
if group.openSlots > 0 {
Text("\(group.openSlots) offen")
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.foregroundStyle(LP.open)
}
}
.padding(.horizontal, horizontalPadding)
.padding(.vertical, 7)
.frame(width: horizontalPadding * 2 + dateWidth + liturgyWidth + churchWidth * 4 + gap * 5, alignment: .leading)
.background(LP.paperDeep.opacity(0.55))
.overlay(alignment: .top) { Hairline() }
.overlay(alignment: .bottom) { Hairline().opacity(0.55) }
}
private struct MonthGroup: Identifiable {
var id: String
var title: String
var rows: [DayPlanRow]
var serviceCount: Int
var openSlots: Int
}
private var monthGroups: [MonthGroup] {
var groups: [MonthGroup] = []
for row in model.filteredRows {
let key = DayMath.monthKey(row.date)
if groups.last?.id == key {
groups[groups.count - 1].rows.append(row)
groups[groups.count - 1].serviceCount += row.services.count
groups[groups.count - 1].openSlots += row.openSlots
} else {
let title = "\(DayMath.monthName(row.date)) \(DayMath.year(row.date))"
groups.append(MonthGroup(
id: key,
title: title,
rows: [row],
serviceCount: row.services.count,
openSlots: row.openSlots
))
}
}
return groups
}
}
private struct ChurchColumnHeader: View {
var church: Church
var width: CGFloat
var body: some View {
HStack(spacing: 8) {
ChurchGlyph(symbol: church.symbol, tint: LP.churchColor(church.colorHex), lineWidth: 1.5)
.frame(width: 34, height: 25)
VStack(alignment: .leading, spacing: 2) {
Text(church.name)
.font(LP.serifSubhead)
.foregroundStyle(LP.ink)
.lineLimit(1)
Text(church.address)
.font(.system(size: 8, weight: .medium))
.foregroundStyle(LP.inkTertiary)
.lineLimit(1)
}
Spacer(minLength: 0)
Image(systemName: "info.circle")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary.opacity(0.65))
}
.frame(width: width, alignment: .leading)
.help("\(church.name)\n\(church.address)\n\(church.notes)\n\n\(church.symbol.caption)")
}
}
private struct DayRow: View {
@EnvironmentObject private var model: PlanModel
var row: DayPlanRow
var churchWidth: CGFloat
var dateWidth: CGFloat
var liturgyWidth: CGFloat
var gap: CGFloat
var horizontalPadding: CGFloat
private var day: LiturgicalDay? { row.liturgicalDay }
private var isHighFeast: Bool { day?.isHighFeast == true }
private var isFeast: Bool { day?.isFeast == true }
private var isSunday: Bool { day?.isSunday == true || DayMath.isSunday(row.date) }
private var isSpecialDay: Bool { isSunday || isFeast || day?.isObligation == true }
var body: some View {
HStack(alignment: .top, spacing: gap) {
dateCell
.frame(width: dateWidth, alignment: .leading)
liturgyCell
.frame(width: liturgyWidth, alignment: .leading)
ForEach(model.churches) { church in
churchCell(church: church)
.frame(width: churchWidth, alignment: .topLeading)
}
}
.padding(.horizontal, horizontalPadding)
.padding(.vertical, 9)
.background(background)
.overlay(alignment: .bottom) {
Rectangle()
.fill(LP.line.opacity(isSpecialDay ? 0.55 : 0.32))
.frame(height: 0.7)
}
}
private var background: some View {
Group {
if isHighFeast {
LinearGradient(colors: [LP.feastWash, LP.sundayWash.opacity(0.6)],
startPoint: .leading, endPoint: .trailing)
} else if isSunday || day?.isObligation == true {
LP.sundayWash.opacity(0.72)
} else if isFeast {
LP.feastWash.opacity(0.42)
} else {
Color.clear
}
}
}
private var accentColor: Color {
guard let day else { return LP.line }
return LP.liturgicalColor(day.color)
}
private var dateCell: some View {
HStack(spacing: 8) {
RoundedRectangle(cornerRadius: 2)
.fill(accentColor)
.frame(width: 3, height: 46)
.opacity(isSpecialDay ? 1 : 0.35)
VStack(alignment: .leading, spacing: 1) {
Text(DayMath.shortWeekdayName(row.date).uppercased())
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(isSunday ? LP.burgundy : LP.inkTertiary)
HStack(alignment: .firstTextBaseline, spacing: 3) {
Text("\(DayMath.dayNumber(row.date))")
.font(.system(size: 24, weight: .semibold, design: .serif))
.foregroundStyle(isHighFeast ? LP.gold : (isSunday ? LP.burgundy : LP.ink))
Text(DayMath.shortMonthName(row.date))
.font(.system(size: 9, weight: .medium, design: .rounded))
.foregroundStyle(LP.inkTertiary)
}
if isSunday {
Text("SONNTAG")
.font(.system(size: 7, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(LP.burgundy.opacity(0.8))
} else if day?.isObligation == true {
Text("GEBOTEN")
.font(.system(size: 7, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(LP.burgundy.opacity(0.8))
} else {
Text(DayMath.yearString(row.date))
.font(.system(size: 7.5, weight: .medium, design: .rounded))
.foregroundStyle(LP.inkTertiary.opacity(0.8))
}
}
}
}
private var liturgyCell: some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 5) {
if let day {
RankBadge(day: day)
if day.rank == .weekday, !day.isSunday, !day.isObligation {
Text(day.season.shortTitle.uppercased())
.font(.system(size: 7.5, weight: .bold, design: .rounded))
.tracking(0.5)
.foregroundStyle(LP.inkTertiary)
}
}
Spacer(minLength: 0)
if let day, day.isFeast {
Image(systemName: day.symbol.symbolName)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(isHighFeast ? LP.gold : LP.burgundy.opacity(0.7))
.help("\(day.symbol.label) · \(day.rank.label)")
}
}
Text(day?.displayTitle ?? "—")
.font(.system(size: 13.5, weight: isSpecialDay ? .semibold : .regular, design: .serif))
.foregroundStyle(isHighFeast ? LP.ink : (isSunday ? LP.burgundy : LP.ink))
.lineLimit(2)
.fixedSize(horizontal: false, vertical: true)
if let day, !day.readings.isEmpty {
HStack(alignment: .top, spacing: 4) {
Image(systemName: "book.closed")
.font(.system(size: 7.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
.padding(.top, 1)
Text(day.readings.shortLabel)
.font(.system(size: 8.8, weight: .regular))
.foregroundStyle(LP.inkSecondary)
.lineLimit(2)
.fixedSize(horizontal: false, vertical: true)
}
} else if day?.title == "Karsamstag" {
Text("Keine Eucharistiefeier am Tag")
.font(.system(size: 8.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
}
.padding(.top, 1)
.help(liturgyHelp)
}
private var liturgyHelp: String {
guard let day else { return DayMath.longString(row.date) }
var parts = ["\(DayMath.longString(row.date))", day.title]
if !day.remark.isEmpty { parts.append(day.remark) }
if !day.badgeText.isEmpty { parts.append(day.badgeText) }
parts.append("Liturgische Farbe: \(day.color.label)")
if !day.readings.isEmpty { parts.append(day.readings.fullLabel) }
if day.isObligation { parts.append("Gebotener Feiertag") }
return parts.joined(separator: "\n")
}
private func churchCell(church: Church) -> some View {
let services = row.services.filter { $0.church.id == church.id }
return Group {
if services.isEmpty {
HStack {
Spacer()
Image(systemName: "circle.dotted")
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary.opacity(0.18))
Spacer()
}
.frame(minHeight: 58)
} else {
VStack(spacing: 5) {
ForEach(services) { service in
ServiceCard(service: service, liturgy: day)
}
}
}
}
}
}
private struct ServiceCard: View {
@EnvironmentObject private var model: PlanModel
var service: ServiceWithAssignments
var liturgy: LiturgicalDay?
private var churchColor: Color { LP.churchColor(service.church.colorHex) }
var body: some View {
Button {
model.serviceDetail = ServiceDetailRequest(serviceID: service.service.id)
} label: {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 5) {
Text(service.service.timeLabel)
.font(.system(size: 10.5, weight: .bold, design: .rounded))
.foregroundStyle(churchColor)
Text(service.service.title)
.font(.system(size: 9.5, weight: .semibold))
.foregroundStyle(LP.ink)
.lineLimit(1)
if service.service.kind == .special {
Text("S")
.font(.system(size: 7, weight: .black, design: .rounded))
.foregroundStyle(.white)
.frame(width: 12, height: 12)
.background(Circle().fill(LP.burgundy))
}
Spacer(minLength: 0)
if service.isFullyStaffed {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 9))
.foregroundStyle(LP.success.opacity(0.8))
} else {
Text("\(service.openSlots)")
.font(.system(size: 7.5, weight: .bold, design: .rounded))
.foregroundStyle(LP.open)
.padding(.horizontal, 4)
.padding(.vertical, 1)
.background(Capsule().fill(LP.openSoft))
}
}
ForEach(Role.allCases) { role in
if service.service.requiredCount(for: role) > 0 {
roleLine(role: role)
}
}
}
.padding(.horizontal, 7)
.padding(.vertical, 6)
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.fill(service.service.kind == .special ? LP.burgundySoft.opacity(0.55) : LP.card)
)
.overlay(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.strokeBorder(service.service.kind == .special ? LP.burgundy.opacity(0.28) : LP.line.opacity(0.55), lineWidth: 0.8)
)
.overlay(alignment: .leading) {
RoundedRectangle(cornerRadius: 1)
.fill(churchColor.opacity(0.55))
.frame(width: 2.2)
.padding(.vertical, 6)
}
}
.buttonStyle(.plain)
.help(helpText)
}
private func roleLine(role: Role) -> some View {
let assigned = service.assignments(for: role)
let open = service.openSlots(for: role)
return HStack(spacing: 3) {
Image(systemName: role.symbolName)
.font(.system(size: 7))
.foregroundStyle(role == .lector ? LP.accent : LP.burgundy)
.frame(width: 10)
if assigned.isEmpty {
Text(open > 1 ? "\(open)× \(role.title) offen" : "\(role.title) offen")
.font(.system(size: 8.5, weight: .medium))
.foregroundStyle(LP.open)
.padding(.horizontal, 4)
.padding(.vertical, 1)
.background(Capsule().fill(LP.openSoft.opacity(0.7)))
} else {
ForEach(assigned) { assignment in
if let person = model.peopleByID[assignment.personID] {
PersonMiniChip(person: person, role: role, color: churchColor)
}
}
if open > 0 {
Text("+\(open)")
.font(.system(size: 8, weight: .bold, design: .rounded))
.foregroundStyle(LP.open)
}
}
Spacer(minLength: 0)
}
}
private var helpText: String {
var lines = [
"\(service.church.name) · \(DayMath.longString(service.service.date)) · \(service.service.timeLabel)",
service.service.title
]
for role in Role.allCases {
let names = service.assignments(for: role).compactMap { model.peopleByID[$0.personID]?.fullName }
if service.service.requiredCount(for: role) > 0 {
lines.append("\(role.title): \(names.isEmpty ? "offen" : names.joined(separator: ", "))")
}
}
if let liturgy {
if !liturgy.readings.isEmpty { lines.append(liturgy.readings.shortLabel) }
if !liturgy.remark.isEmpty { lines.append(liturgy.remark) }
}
if !service.service.notes.isEmpty { lines.append(service.service.notes) }
lines.append("Klicken zum Bearbeiten")
return lines.joined(separator: "\n")
}
}
private extension DayMath {
static func yearString(_ date: Date) -> String {
String(year(date))
}
}
@@ -0,0 +1,448 @@
import SwiftUI
import LektorenPlanCore
struct ServiceDetailSheet: View {
@EnvironmentObject private var model: PlanModel
@Environment(\.dismiss) private var dismiss
let serviceID: String
@State private var selectedRole: Role = .lector
@State private var confirmDelete = false
private var item: ServiceWithAssignments? {
model.serviceWithAssignments(id: serviceID)
}
var body: some View {
VStack(spacing: 0) {
if let item {
header(item: item)
Hairline()
HStack(alignment: .top, spacing: 0) {
leftColumn(item: item)
.frame(width: 330)
Rectangle().fill(LP.line.opacity(0.6)).frame(width: 1)
rightColumn(item: item)
.frame(maxWidth: .infinity)
}
SheetFooter {
if item.service.kind == .special {
Button {
model.serviceDetail = nil
model.specialServiceEditor = SpecialServiceRequest(
churchID: item.service.churchID,
date: item.service.date,
service: item.service
)
} label: {
HStack(spacing: 5) {
Image(systemName: "pencil")
Text("Bearbeiten")
}
.font(.system(size: 11.5, weight: .medium))
.foregroundStyle(LP.inkSecondary)
}
.buttonStyle(.plain)
Button {
confirmDelete = true
} label: {
Image(systemName: "trash")
.font(.system(size: 11.5, weight: .medium))
.foregroundStyle(LP.danger)
}
.buttonStyle(.plain)
.help("Sondergottesdienst löschen")
}
Spacer()
SecondaryActionButton(title: "Schließen", icon: "xmark") { dismiss() }
PrimaryActionButton(title: "Automatisch besetzen", icon: "wand.and.stars") {
model.autoFill(serviceID: serviceID)
}
}
} else {
VStack(spacing: 12) {
ProgressView()
Text("Gottesdienst wird geladen…")
.font(.system(size: 11))
.foregroundStyle(LP.inkTertiary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.sheetSurface(width: 820, height: 660)
.onAppear {
if let item, item.service.lectorsNeeded == 0 {
selectedRole = .helper
}
}
.confirmationDialog(
"Sondergottesdienst löschen?",
isPresented: $confirmDelete,
titleVisibility: .visible
) {
Button("Löschen", role: .destructive) {
if let item {
model.deleteService(item.service)
}
dismiss()
}
Button("Abbrechen", role: .cancel) {}
} message: {
Text("Der Termin und alle zugehörigen Einsätze werden entfernt.")
}
}
// MARK: - Header
private func header(item: ServiceWithAssignments) -> some View {
let churchColor = LP.churchColor(item.church.colorHex)
let day = model.liturgicalDays[item.service.dateKey]
return HStack(alignment: .top, spacing: 14) {
ZStack {
RoundedRectangle(cornerRadius: 12, style: .continuous)
.fill(churchColor.opacity(0.10))
ChurchGlyph(symbol: item.church.symbol, tint: churchColor, lineWidth: 1.5, showGround: false)
.padding(7)
}
.frame(width: 52, height: 52)
.overlay(RoundedRectangle(cornerRadius: 12, style: .continuous)
.strokeBorder(churchColor.opacity(0.22), lineWidth: 0.8))
VStack(alignment: .leading, spacing: 3) {
HStack(spacing: 6) {
Text(item.church.name)
.font(.system(size: 10, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(churchColor)
if item.service.kind == .special {
TinyBadge(text: "SONDERGOTTESDIENST", color: LP.burgundy, filled: true)
}
if !item.isFullyStaffed {
TinyBadge(text: "\(item.openSlots) OFFEN", color: LP.open, filled: true)
}
}
Text(item.service.title)
.font(LP.serifHeadline)
.foregroundStyle(LP.ink)
Text("\(DayMath.longString(item.service.date)) · \(item.service.timeLabel) Uhr")
.font(.system(size: 10.5))
.foregroundStyle(LP.inkSecondary)
if let day {
Text(day.displayTitle + (day.remark.isEmpty ? "" : " · \(day.remark)"))
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
}
}
Spacer(minLength: 12)
VStack(alignment: .trailing, spacing: 5) {
HStack(spacing: 10) {
requirementBadge(role: .lector, needed: item.service.lectorsNeeded)
requirementBadge(role: .helper, needed: item.service.helpersNeeded)
}
if item.service.locked {
Label("Gesperrt", systemImage: "lock.fill")
.font(.system(size: 9, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
}
}
.padding(.horizontal, 22)
.padding(.vertical, 18)
}
private func requirementBadge(role: Role, needed: Int) -> some View {
HStack(spacing: 4) {
Image(systemName: role.symbolName)
.font(.system(size: 9, weight: .semibold))
Text("\(needed)×")
.font(.system(size: 10, weight: .bold, design: .rounded))
}
.foregroundStyle(needed == 0 ? LP.inkTertiary : (role == .lector ? LP.accent : LP.burgundy))
.padding(.horizontal, 7)
.padding(.vertical, 3)
.background(Capsule().fill((role == .lector ? LP.accent : LP.burgundy).opacity(needed == 0 ? 0.04 : 0.10)))
}
// MARK: - Left column
private func leftColumn(item: ServiceWithAssignments) -> some View {
ScrollView {
VStack(alignment: .leading, spacing: 18) {
if let day = model.liturgicalDays[item.service.dateKey] {
liturgyCard(day)
}
VStack(alignment: .leading, spacing: 9) {
SectionLabel(title: "Aktuelle Besetzung")
ForEach(Role.allCases) { role in
let needed = item.service.requiredCount(for: role)
if needed > 0 {
assignmentGroup(item: item, role: role, needed: needed)
}
}
}
if !item.service.notes.isEmpty {
VStack(alignment: .leading, spacing: 5) {
SectionLabel(title: "Notiz")
Text(item.service.notes)
.font(.system(size: 10.5))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
.padding(20)
}
}
private func liturgyCard(_ day: LiturgicalDay) -> some View {
VStack(alignment: .leading, spacing: 7) {
HStack(spacing: 6) {
Image(systemName: day.symbol.symbolName)
.font(.system(size: 11, weight: .medium))
.foregroundStyle(day.isHighFeast ? LP.gold : LP.burgundy)
Text("LITURGIE DES TAGES")
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(1)
.foregroundStyle(LP.inkTertiary)
Spacer()
if day.isHighFeast {
TinyBadge(text: "HOCHFEST", color: LP.gold)
}
}
Text(day.displayTitle)
.font(LP.serifSubhead)
.foregroundStyle(LP.ink)
if !day.readings.isEmpty {
VStack(alignment: .leading, spacing: 4) {
readingLine("1. Lesung", day.readings.first)
readingLine("Psalm", day.readings.psalm)
readingLine("2. Lesung", day.readings.second)
readingLine("Evangelium", day.readings.gospel)
}
} else {
Text("Für diesen Tag sind keine Lesungen hinterlegt.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
}
Text(day.source)
.font(.system(size: 7.5))
.foregroundStyle(LP.inkTertiary.opacity(0.8))
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
.background(RoundedRectangle(cornerRadius: 10).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.8))
}
private func readingLine(_ label: String, _ value: String) -> some View {
if value.isEmpty {
return AnyView(EmptyView())
}
return AnyView(HStack(alignment: .top, spacing: 5) {
Text(label)
.font(.system(size: 8.5, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
.frame(width: 62, alignment: .leading)
Text(value)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
})
}
private func assignmentGroup(item: ServiceWithAssignments, role: Role, needed: Int) -> some View {
let assigned = item.assignments(for: role)
return VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 5) {
RepBadge(role: role)
Text("\(assigned.count) von \(needed)")
.font(.system(size: 9, weight: .medium, design: .rounded))
.foregroundStyle(assigned.count >= needed ? LP.success : LP.open)
Spacer()
}
if assigned.isEmpty {
Text("Noch offen")
.font(.system(size: 10))
.foregroundStyle(LP.open)
.padding(.leading, 2)
} else {
ForEach(assigned) { assignment in
if let person = model.peopleByID[assignment.personID] {
HStack(spacing: 8) {
Avatar(initials: person.initials, color: LP.churchColor(item.church.colorHex), size: 24)
VStack(alignment: .leading, spacing: 1) {
Text(person.fullName)
.font(.system(size: 11, weight: .medium))
.foregroundStyle(LP.ink)
Text(person.roleLabel)
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
}
Spacer()
Button {
model.toggleAssignmentLock(assignment)
} label: {
Image(systemName: assignment.locked ? "lock.fill" : "lock.open")
.font(.system(size: 9.5))
.foregroundStyle(assignment.locked ? LP.accent : LP.inkTertiary)
}
.buttonStyle(.plain)
.help(assignment.locked ? "Sperre aufheben" : "Einsatz sperren")
Button {
model.assign(serviceID: item.service.id, role: role, personID: nil)
} label: {
Image(systemName: "xmark.circle.fill")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
}
.buttonStyle(.plain)
.help("Einsatz entfernen")
}
.padding(.horizontal, 8)
.padding(.vertical, 5)
.background(RoundedRectangle(cornerRadius: 8).fill(LP.card))
.overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.8))
}
}
}
}
}
// MARK: - Right column (candidates)
private func rightColumn(item: ServiceWithAssignments) -> some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 10) {
Text("Vorschläge")
.font(.system(size: 10, weight: .bold, design: .rounded))
.tracking(1)
.foregroundStyle(LP.inkTertiary)
Picker("", selection: $selectedRole) {
ForEach(Role.allCases) { role in
Text(role.title).tag(role)
}
}
.labelsHidden()
.pickerStyle(.segmented)
.frame(width: 230)
.disabled(item.service.lectorsNeeded == 0 || item.service.helpersNeeded == 0)
Spacer()
Text("Fairness · Präferenzen · Verfügbarkeit")
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
}
.padding(.horizontal, 18)
.padding(.vertical, 12)
Hairline()
let suggestions = model.candidateSuggestions(for: item.service, role: selectedRole)
if suggestions.isEmpty {
EmptyStateView(
icon: "person.crop.circle.badge.questionmark",
title: "Keine Kandidaten",
message: "Für diese Rolle ist derzeit niemand verfügbar oder alle geeigneten Personen sind bereits eingeteilt."
)
} else {
ScrollView {
LazyVStack(spacing: 6) {
ForEach(Array(suggestions.enumerated()), id: \.element.id) { index, candidate in
candidateRow(candidate, rank: index + 1, item: item)
}
}
.padding(14)
}
}
}
}
private func candidateRow(_ candidate: CandidateSuggestion, rank: Int, item: ServiceWithAssignments) -> some View {
HStack(spacing: 9) {
Text("\(rank)")
.font(.system(size: 9, weight: .bold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
.frame(width: 18)
Avatar(initials: candidate.person.initials,
color: candidate.blocked ? LP.inkTertiary : LP.churchColor(item.church.colorHex),
size: 26)
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 5) {
Text(candidate.person.fullName)
.font(.system(size: 11.5, weight: .medium))
.foregroundStyle(candidate.blocked ? LP.inkTertiary : LP.ink)
if candidate.preferred {
Image(systemName: "star.fill")
.font(.system(size: 7))
.foregroundStyle(LP.gold)
.help("Entspricht einer Präferenz")
}
if candidate.person.roles.contains(.lector) && candidate.person.roles.contains(.helper) {
TinyBadge(text: "L+K", color: LP.accent)
}
}
HStack(spacing: 6) {
Text("\(candidate.totalAssignments) Einsätze im Zeitraum")
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
ForEach(candidate.warnings, id: \.self) { warning in
Text(warning)
.font(.system(size: 8, weight: .medium))
.foregroundStyle(LP.open)
.padding(.horizontal, 4)
.padding(.vertical, 1)
.background(Capsule().fill(LP.openSoft.opacity(0.75)))
}
}
}
Spacer(minLength: 4)
Button {
model.assign(serviceID: item.service.id, role: selectedRole, personID: candidate.person.id)
} label: {
HStack(spacing: 3) {
Image(systemName: "plus")
.font(.system(size: 8, weight: .bold))
Text("Einteilen")
.font(.system(size: 9.5, weight: .semibold))
}
.foregroundStyle(candidate.blocked ? LP.inkTertiary : .white)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(
Capsule().fill(candidate.blocked ? LP.cardMuted : LP.accent)
)
}
.buttonStyle(.plain)
.disabled(candidate.blocked)
.help(candidate.blocked ? candidate.warnings.joined(separator: ", ") : "Für diesen Dienst einteilen")
}
.padding(.horizontal, 9)
.padding(.vertical, 7)
.background(RoundedRectangle(cornerRadius: 9).fill(candidate.blocked ? LP.cardMuted.opacity(0.5) : LP.card))
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(LP.line.opacity(0.55), lineWidth: 0.8))
.opacity(candidate.blocked ? 0.72 : 1)
}
}
private struct RepBadge: View {
var role: Role
var body: some View {
HStack(spacing: 3) {
Image(systemName: role.symbolName)
.font(.system(size: 7.5, weight: .semibold))
Text(role.title)
.font(.system(size: 9, weight: .semibold))
}
.foregroundStyle(role == .lector ? LP.accent : LP.burgundy)
}
}
@@ -0,0 +1,343 @@
import SwiftUI
import LektorenPlanCore
struct ServiceOrderView: View {
@EnvironmentObject private var model: PlanModel
@State private var showExceptions = false
private let columns = [GridItem(.adaptive(minimum: 500), spacing: 14)]
var body: some View {
VStack(spacing: 14) {
PageHeader(
eyebrow: "Gottesdienstordnung",
title: "Wiederkehrende Zeiten",
subtitle: "Regelmäßige Gottesdienste je Kirche, Sondertermine und Ausnahmen im Kirchenjahr."
) {
HStack(spacing: 8) {
SecondaryActionButton(title: "Ausnahmen", icon: "calendar.badge.exclamationmark") {
withAnimation(.easeInOut(duration: 0.18)) {
showExceptions.toggle()
}
}
SecondaryActionButton(title: "Termine erzeugen", icon: "arrow.clockwise") {
model.generateServices()
}
.help("Erzeugt aus den Vorlagen alle Gottesdienste im gewählten Zeitraum")
PrimaryActionButton(title: "Sondergottesdienst", icon: "sparkles") {
model.specialServiceEditor = SpecialServiceRequest(
churchID: model.churches.first?.id,
date: DayMath.today()
)
}
}
}
if showExceptions {
exceptionsPanel
.transition(.move(edge: .top).combined(with: .opacity))
}
ScrollView {
VStack(alignment: .leading, spacing: 20) {
LazyVGrid(columns: columns, alignment: .leading, spacing: 14) {
ForEach(model.churches) { church in
churchCard(church)
}
}
specialsSection
}
.padding(.bottom, 16)
}
}
.padding(.horizontal, 22)
.padding(.top, 30)
.padding(.bottom, 18)
}
// MARK: - Church card
private func churchCard(_ church: Church) -> some View {
let templates = model.templates(for: church.id)
let color = LP.churchColor(church.colorHex)
return SurfaceCard(padding: 0, radius: 15, background: LP.card) {
VStack(spacing: 0) {
HStack(spacing: 11) {
ZStack {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(color.opacity(0.10))
ChurchGlyph(symbol: church.symbol, tint: color, lineWidth: 1.5, showGround: false)
.padding(5)
}
.frame(width: 44, height: 44)
.overlay(RoundedRectangle(cornerRadius: 10, style: .continuous)
.strokeBorder(color.opacity(0.22), lineWidth: 0.8))
VStack(alignment: .leading, spacing: 2) {
Text(church.name)
.font(LP.serifHeadline)
.foregroundStyle(LP.ink)
Text(church.address)
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
Text(templates.count == 1 ? "1 regelmäßiger Termin" : "\(templates.count) regelmäßige Termine")
.font(.system(size: 9, weight: .medium))
.foregroundStyle(LP.inkSecondary)
}
Spacer()
Button {
model.templateEditor = TemplateEditorRequest(
template: nil,
churchID: church.id
)
} label: {
Image(systemName: "plus")
.font(.system(size: 10, weight: .bold))
.foregroundStyle(.white)
.frame(width: 24, height: 24)
.background(Circle().fill(color))
}
.buttonStyle(.plain)
.help("Neuen regelmäßigen Gottesdienst für \(church.name) anlegen")
}
.padding(14)
Hairline()
if templates.isEmpty {
Text("Noch keine Gottesdienstzeiten hinterlegt.")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(14)
} else {
VStack(spacing: 0) {
ForEach(templates) { template in
templateRow(template, color: color)
if template.id != templates.last?.id {
Hairline().opacity(0.5)
}
}
}
}
}
}
}
private func templateRow(_ template: ServiceTemplate, color: Color) -> some View {
let exceptionCount = model.exceptions.filter { $0.templateID == template.id }.count
return HStack(spacing: 10) {
VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 5) {
Text(template.weekdayLabel)
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
Text(template.timeLabel)
.font(.system(size: 11, weight: .bold, design: .rounded))
.foregroundStyle(color)
}
Text(template.title)
.font(.system(size: 11.5, weight: .medium))
.foregroundStyle(LP.ink)
}
Spacer(minLength: 4)
HStack(spacing: 5) {
if template.lectorsNeeded > 0 {
requirementChip(role: .lector, count: template.lectorsNeeded)
}
if template.helpersNeeded > 0 {
requirementChip(role: .helper, count: template.helpersNeeded)
}
}
if exceptionCount > 0 {
Text("\(exceptionCount)× ausgesetzt")
.font(.system(size: 7.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
.help("Ausnahmen: \(model.exceptions.filter { $0.templateID == template.id }.map { DayMath.mediumString($0.date) }.joined(separator: ", "))")
}
if !template.active {
TinyBadge(text: "INAKTIV", color: LP.inkTertiary)
}
Button {
model.templateEditor = TemplateEditorRequest(template: template, churchID: template.churchID)
} label: {
Image(systemName: "pencil")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.frame(width: 22, height: 22)
.background(Circle().fill(LP.cardMuted))
}
.buttonStyle(.plain)
.help("Gottesdienst bearbeiten")
}
.padding(.horizontal, 14)
.padding(.vertical, 9)
.opacity(template.active ? 1 : 0.6)
}
private func requirementChip(role: Role, count: Int) -> some View {
HStack(spacing: 3) {
Text(role == .lector ? "L" : "K")
.font(.system(size: 7.5, weight: .bold, design: .rounded))
.opacity(0.75)
Text("\(count)")
.font(.system(size: 8.5, weight: .bold, design: .rounded))
}
.foregroundStyle(role == .lector ? LP.accent : LP.burgundy)
.padding(.horizontal, 5)
.padding(.vertical, 1.5)
.background(Capsule().fill((role == .lector ? LP.accent : LP.burgundy).opacity(0.09)))
.help(role.title)
}
// MARK: - Specials
private var specialsSection: some View {
SurfaceCard(padding: 0, radius: 15, background: LP.card) {
VStack(spacing: 0) {
HStack(spacing: 9) {
Image(systemName: "sparkles")
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(LP.burgundy)
VStack(alignment: .leading, spacing: 1) {
Text("Sondergottesdienste")
.font(LP.serifSubhead)
.foregroundStyle(LP.ink)
Text("Einmalige Termine und Hochfeste mit abweichender Ordnung")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
Spacer()
SecondaryActionButton(title: "Hinzufügen", icon: "plus") {
model.specialServiceEditor = SpecialServiceRequest(
churchID: model.churches.first?.id,
date: DayMath.today()
)
}
}
.padding(14)
Hairline()
let specials = model.upcomingSpecials()
if specials.isEmpty {
Text("Keine anstehenden Sondergottesdienste.")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(14)
} else {
VStack(spacing: 0) {
ForEach(specials, id: \.id) { service in
specialRow(service)
if service.id != specials.last?.id {
Hairline().opacity(0.5)
}
}
}
}
}
}
}
private func specialRow(_ service: ServiceOccurrence) -> some View {
let church = model.churchByID[service.churchID]
let color = church.map { LP.churchColor($0.colorHex) } ?? LP.burgundy
return HStack(spacing: 11) {
VStack(spacing: 0) {
Text(DayMath.shortWeekdayName(service.date).uppercased())
.font(.system(size: 7, weight: .bold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
Text("\(DayMath.dayNumber(service.date)).")
.font(.system(size: 15, weight: .semibold, design: .serif))
.foregroundStyle(color)
Text(DayMath.shortMonthName(service.date))
.font(.system(size: 7.5))
.foregroundStyle(LP.inkTertiary)
}
.frame(width: 34)
.padding(.vertical, 3)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.cardMuted))
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 5) {
Text(service.timeLabel)
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.foregroundStyle(color)
Text(service.title)
.font(.system(size: 11, weight: .medium))
.foregroundStyle(LP.ink)
}
Text([church?.name, service.notes].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.lineLimit(1)
}
Spacer()
requirementChip(role: .lector, count: service.lectorsNeeded)
requirementChip(role: .helper, count: service.helpersNeeded)
Button {
model.serviceDetail = ServiceDetailRequest(serviceID: service.id)
} label: {
Image(systemName: "pencil")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.frame(width: 22, height: 22)
.background(Circle().fill(LP.cardMuted))
}
.buttonStyle(.plain)
}
.padding(.horizontal, 14)
.padding(.vertical, 8)
}
// MARK: - Exceptions
private var exceptionsPanel: some View {
let exceptions = model.exceptions.sorted { $0.date < $1.date }.filter { $0.date >= DayMath.adding(days: -30, to: DayMath.today()) }
return SurfaceCard(padding: 14, radius: 14, background: LP.goldSoft.opacity(0.35)) {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("AUSSETZUNGEN & AUSNAHMEN")
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(1.1)
.foregroundStyle(LP.inkTertiary)
Spacer()
Text("\(exceptions.count) Einträge")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
if exceptions.isEmpty {
Text("Keine Ausnahmen erfasst.")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
} else {
FlowLayout(spacing: 6) {
ForEach(exceptions) { exception in
if let template = model.templates.first(where: { $0.id == exception.templateID }),
let church = model.churchByID[template.churchID] {
HStack(spacing: 4) {
Image(systemName: "calendar.badge.minus")
.font(.system(size: 7.5))
Text("\(DayMath.mediumString(exception.date)) · \(church.shortName) \(template.timeLabel)")
.font(.system(size: 8.5, weight: .medium))
if !exception.reason.isEmpty {
Text("(\(exception.reason))")
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
}
}
.foregroundStyle(LP.inkSecondary)
.padding(.horizontal, 7)
.padding(.vertical, 4)
.background(Capsule().fill(LP.card))
.overlay(Capsule().strokeBorder(LP.line.opacity(0.6), lineWidth: 0.7))
}
}
}
}
}
}
}
}
@@ -0,0 +1,365 @@
import SwiftUI
import LektorenPlanCore
struct SettingsView: View {
@EnvironmentObject private var model: PlanModel
@State private var autoSync = true
@State private var respectWeekdays = true
@State private var fairnessWeight = 2.2
@State private var confirmReset = false
var body: some View {
VStack(spacing: 14) {
PageHeader(
eyebrow: "Einstellungen",
title: "Kalender, Planung & Daten",
subtitle: "Liturgische Quelle, Planungsvorgaben und lokale Datenhaltung."
) {
HStack(spacing: 8) {
SecondaryActionButton(title: "Datenbank öffnen", icon: "folder") {
model.openDatabaseFolder()
}
PrimaryActionButton(title: "Kalender aktualisieren", icon: "arrow.triangle.2.circlepath") {
Task { await model.syncLiturgy() }
}
}
}
ScrollView {
VStack(alignment: .leading, spacing: 14) {
liturgicalSection
planningSection
databaseSection
aboutSection
}
.padding(.bottom, 16)
}
}
.padding(.horizontal, 22)
.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()
}
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.")
}
}
// MARK: - Liturgy
private var liturgicalSection: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 14) {
sectionHeader(
icon: "book.closed",
title: "Liturgischer Kalender",
subtitle: "Erzbistum Köln · Bezug über www.eucharistiefeier.de",
tint: LP.gold
)
HStack(spacing: 14) {
infoTile(
label: "Letzte Aktualisierung",
value: model.lastSync.map { DayMath.mediumString($0) } ?? "Noch nicht online aktualisiert",
detail: model.lastSync == nil ? "Offline-Snapshot aktiv" : "Online-Quelle",
tint: model.lastSync == nil ? LP.open : LP.success
)
infoTile(
label: "Verfügbare Jahre",
value: availableYearsLabel,
detail: "in der Datenbank",
tint: LP.accent
)
infoTile(
label: "Quelle",
value: "eucharistiefeier.de",
detail: "fair use, manuelle Abfrage",
tint: LP.burgundy
)
Spacer(minLength: 0)
}
HStack(spacing: 10) {
Toggle(isOn: $autoSync) {
VStack(alignment: .leading, spacing: 1) {
Text("Tägliche automatische Aktualisierung")
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
Text("Beim Start wird höchstens einmal pro Tag der aktuelle Jahrgang geladen.")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
}
.toggleStyle(.checkbox)
.onChange(of: autoSync) { _, newValue in
model.db.setSetting("autoSyncLiturgy", value: newValue ? "1" : "0")
}
Spacer()
SecondaryActionButton(title: "Jahrgänge aktualisieren", icon: "arrow.clockwise") {
Task { await model.syncLiturgy(years: Array(Set(model.range.days.map { DayMath.year($0) })).sorted()) }
}
.disabled(model.isSyncing)
}
if model.isSyncing {
HStack(spacing: 7) {
ProgressView().controlSize(.small)
Text(model.syncMessage.isEmpty ? "Lade Kalender…" : model.syncMessage)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
}
}
Text("Die liturgischen Daten werden für die Darstellung von Hochfesten, liturgischen Farben und Tageslesungen verwendet. Bei fehlender Internetverbindung steht ein mitgelieferter Offline-Bestand zur Verfügung. Die Daten bleiben Eigentum der Quelle und werden ausschließlich zur Anzeige genutzt.")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
private var availableYearsLabel: String {
let years = (try? model.db.liturgicalYears()) ?? []
return years.isEmpty ? "—" : years.map(String.init).joined(separator: ", ")
}
// MARK: - Planning
private var planningSection: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 14) {
sectionHeader(
icon: "wand.and.stars",
title: "Planungsvorgaben",
subtitle: "Gewichtung und harte Randbedingungen der automatischen Verteilung",
tint: LP.accent
)
Toggle(isOn: $respectWeekdays) {
VStack(alignment: .leading, spacing: 1) {
Text("Bevorzugte Einsatztage als Ausschluss behandeln")
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
Text("Wenn aktiv, werden Personen nur an ihren hinterlegten Wochentagen eingeplant.")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
}
.toggleStyle(.checkbox)
.onChange(of: respectWeekdays) { _, newValue in
model.db.setSetting("respectPreferredWeekdays", value: newValue ? "1" : "0")
}
VStack(alignment: .leading, spacing: 5) {
HStack {
Text("Gewicht der Fairness")
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
Spacer()
Text(String(format: "%.1f", fairnessWeight))
.font(.system(size: 10.5, weight: .semibold, design: .rounded))
.foregroundStyle(LP.accent)
}
Slider(value: $fairnessWeight, in: 0.5...4.0)
.tint(LP.accent)
.onChange(of: fairnessWeight) { _, newValue in
let rounded = (newValue * 10).rounded() / 10
if rounded != newValue {
fairnessWeight = rounded
}
model.db.setSetting("fairnessWeight", value: String(format: "%.1f", rounded))
}
HStack {
Text("Vorlieben stärker")
Spacer()
Text("Gleichverteilung stärker")
}
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
}
Hairline()
HStack(spacing: 8) {
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.")
.font(.system(size: 9))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
Spacer()
}
}
}
}
// MARK: - Database
private var databaseSection: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 14) {
sectionHeader(
icon: "internaldrive",
title: "Datenhaltung",
subtitle: "Alle Daten liegen lokal in einer SQLite-Datenbank",
tint: LP.burgundy
)
HStack(alignment: .top, spacing: 12) {
VStack(alignment: .leading, spacing: 4) {
Text("Datenbankpfad")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
Text(model.databasePath)
.font(.system(size: 9.5, design: .monospaced))
.foregroundStyle(LP.inkSecondary)
.textSelection(.enabled)
.lineLimit(2)
}
Spacer()
VStack(alignment: .trailing, spacing: 4) {
Text(model.databaseSizeLabel)
.font(.system(size: 13, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
Text("Dateigröße")
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
}
}
.padding(11)
.background(RoundedRectangle(cornerRadius: 9).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(LP.line.opacity(0.55), lineWidth: 0.8))
HStack(spacing: 9) {
SecondaryActionButton(title: "Im Finder zeigen", icon: "folder") {
model.openDatabaseFolder()
}
SecondaryActionButton(title: "Plan exportieren", icon: "square.and.arrow.up") {
model.exportInteractive(scope: .plan)
}
SecondaryActionButton(title: "Ressourcen exportieren", icon: "square.and.arrow.up") {
model.exportInteractive(scope: .resources)
}
Spacer()
Button {
confirmReset = true
} label: {
HStack(spacing: 5) {
Image(systemName: "arrow.counterclockwise")
Text("Demo-Daten zurücksetzen")
}
.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)
}
}
}
}
// MARK: - About
private var aboutSection: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
HStack(alignment: .top, spacing: 16) {
ZStack {
Circle().fill(LP.accent.opacity(0.10))
ChurchGlyph(symbol: .basilica, tint: LP.accent, lineWidth: 1.3, showGround: false)
.padding(7)
}
.frame(width: 58, height: 58)
.overlay(Circle().strokeBorder(LP.accent.opacity(0.18), lineWidth: 0.8))
VStack(alignment: .leading, spacing: 5) {
Text("LektorenPlan")
.font(LP.serifHeadline)
.foregroundStyle(LP.ink)
Text("Prototyp 0.1 · 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.")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
}
Spacer(minLength: 12)
VStack(alignment: .trailing, spacing: 5) {
Link(destination: URL(string: "https://www.eucharistiefeier.de")!) {
HStack(spacing: 3) {
Text("www.eucharistiefeier.de")
Image(systemName: "arrow.up.right")
.font(.system(size: 7))
}
.font(.system(size: 9, weight: .medium))
.foregroundStyle(LP.accent)
}
Text("SwiftUI · SQLite · Swift Charts")
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
}
}
}
}
// MARK: - Helpers
private func loadSettings() {
autoSync = model.db.setting("autoSyncLiturgy") != "0"
respectWeekdays = model.db.setting("respectPreferredWeekdays") != "0"
fairnessWeight = Double(model.db.setting("fairnessWeight") ?? "") ?? 2.2
}
private func sectionHeader(icon: String, title: String, subtitle: String, tint: Color) -> some View {
HStack(alignment: .top, spacing: 9) {
Image(systemName: icon)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(tint)
.frame(width: 28, height: 28)
.background(Circle().fill(tint.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text(title)
.font(LP.serifSubhead)
.foregroundStyle(LP.ink)
Text(subtitle)
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
}
Spacer()
}
}
private func infoTile(label: String, value: String, detail: String, tint: Color) -> some View {
VStack(alignment: .leading, spacing: 3) {
Text(label.uppercased())
.font(.system(size: 8, weight: .bold, design: .rounded))
.tracking(0.7)
.foregroundStyle(LP.inkTertiary)
Text(value)
.font(.system(size: 11.5, weight: .semibold))
.foregroundStyle(LP.ink)
.lineLimit(1)
Text(detail)
.font(.system(size: 8.5))
.foregroundStyle(tint)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(10)
.background(RoundedRectangle(cornerRadius: 9).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(LP.line.opacity(0.55), lineWidth: 0.8))
}
}
@@ -0,0 +1,145 @@
import SwiftUI
import LektorenPlanCore
// MARK: - Sheet chrome
struct SheetHeader: View {
var icon: String
var title: String
var subtitle: String
var tint: Color = LP.accent
var body: some View {
HStack(alignment: .top, spacing: 13) {
ZStack {
RoundedRectangle(cornerRadius: 11, style: .continuous)
.fill(tint.opacity(0.11))
Image(systemName: icon)
.font(.system(size: 17, weight: .semibold))
.foregroundStyle(tint)
}
.frame(width: 40, height: 40)
VStack(alignment: .leading, spacing: 3) {
Text(title)
.font(LP.serifHeadline)
.foregroundStyle(LP.ink)
Text(subtitle)
.font(.system(size: 11))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
Spacer(minLength: 8)
}
.padding(.horizontal, 22)
.padding(.top, 20)
.padding(.bottom, 14)
}
}
struct SheetFooter<Content: View>: View {
@ViewBuilder var content: Content
var body: some View {
VStack(spacing: 0) {
Hairline()
HStack(spacing: 10) {
content
}
.padding(.horizontal, 22)
.padding(.vertical, 13)
}
.background(LP.card)
}
}
struct FormSection<Content: View>: View {
var title: String
var subtitle: String? = nil
@ViewBuilder var content: Content
var body: some View {
VStack(alignment: .leading, spacing: 10) {
VStack(alignment: .leading, spacing: 2) {
Text(title.uppercased())
.font(.system(size: 9, weight: .bold, design: .rounded))
.tracking(1.2)
.foregroundStyle(LP.inkTertiary)
if let subtitle {
Text(subtitle)
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary.opacity(0.9))
}
}
content
}
}
}
struct LabeledField<Content: View>: View {
var label: String
@ViewBuilder var content: Content
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text(label)
.font(.system(size: 9.5, weight: .semibold))
.foregroundStyle(LP.inkSecondary)
content
}
}
}
struct ChipToggle: View {
var title: String
var icon: String? = nil
var isOn: Bool
var tint: Color = LP.accent
var action: () -> Void
var body: some View {
Button(action: action) {
HStack(spacing: 4) {
if let icon {
Image(systemName: icon)
.font(.system(size: 8.5, weight: .semibold))
}
Text(title)
.font(.system(size: 10, weight: .medium))
}
.foregroundStyle(isOn ? .white : LP.inkSecondary)
.padding(.horizontal, 9)
.padding(.vertical, 5)
.background(
Capsule().fill(isOn ? tint : LP.cardMuted)
)
.overlay(
Capsule().strokeBorder(isOn ? .clear : LP.line.opacity(0.8), lineWidth: 0.8)
)
}
.buttonStyle(.plain)
}
}
struct SheetDestinationPicker: View {
@Binding var selection: String
var churches: [Church]
var body: some View {
Picker("", selection: $selection) {
ForEach(churches) { church in
Text(church.name).tag(church.id)
}
}
.labelsHidden()
.pickerStyle(.menu)
}
}
extension View {
func sheetSurface(width: CGFloat, height: CGFloat) -> some View {
self
.frame(width: width, height: height)
.background(LP.paper)
}
}
@@ -0,0 +1,198 @@
import SwiftUI
import LektorenPlanCore
struct SpecialServiceSheet: View {
@EnvironmentObject private var model: PlanModel
@Environment(\.dismiss) private var dismiss
let request: SpecialServiceRequest
@State private var churchID = ""
@State private var date = DayMath.today()
@State private var timeDate = Date()
@State private var title = ""
@State private var lectorsNeeded = 1
@State private var helpersNeeded = 1
@State private var notes = ""
@State private var useLiturgicalTitle = true
@State private var existing: ServiceOccurrence?
private var isValid: Bool {
!churchID.isEmpty && !title.trimmingCharacters(in: .whitespaces).isEmpty
&& (lectorsNeeded + helpersNeeded) > 0
}
private var liturgicalDay: LiturgicalDay? {
let key = DayMath.key(date)
if let day = model.liturgicalDays[key] { return day }
return LiturgicalCalendarEngine.localDay(for: date)
}
var body: some View {
VStack(spacing: 0) {
SheetHeader(
icon: "sparkles",
title: existing == nil ? "Sondergottesdienst" : "Sondergottesdienst bearbeiten",
subtitle: "Einmaliger Termin außerhalb der regelmäßigen Ordnung – z. B. Christmette, Osternacht oder Patronatsfest.",
tint: LP.burgundy
)
Hairline()
ScrollView {
VStack(alignment: .leading, spacing: 22) {
FormSection(title: "Ort & Zeit") {
HStack(spacing: 12) {
LabeledField(label: "Kirche") {
Picker("", selection: $churchID) {
ForEach(model.churches) { church in
Text(church.name).tag(church.id)
}
}
.labelsHidden()
.pickerStyle(.menu)
}
LabeledField(label: "Datum") {
DatePicker("", selection: $date, displayedComponents: .date)
.labelsHidden()
.datePickerStyle(.field)
}
LabeledField(label: "Uhrzeit") {
DatePicker("", selection: $timeDate, displayedComponents: .hourAndMinute)
.labelsHidden()
.datePickerStyle(.field)
}
}
}
if let day = liturgicalDay {
HStack(spacing: 11) {
Image(systemName: day.symbol.symbolName)
.font(.system(size: 15, weight: .medium))
.foregroundStyle(day.isHighFeast ? LP.gold : LP.burgundy)
.frame(width: 30, height: 30)
.background(Circle().fill((day.isHighFeast ? LP.gold : LP.burgundy).opacity(0.10)))
VStack(alignment: .leading, spacing: 2) {
Text(day.displayTitle)
.font(LP.serifSubhead)
.foregroundStyle(LP.ink)
Text([day.rank.label, day.isObligation ? "gebotener Feiertag" : nil]
.compactMap { $0 }.joined(separator: " · "))
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
if !day.readings.isEmpty {
Text(day.readings.shortLabel)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
.lineLimit(2)
}
}
Spacer()
if !title.isEmpty || useLiturgicalTitle {
SecondaryActionButton(title: "Titel übernehmen", icon: "arrow.down.doc") {
title = day.displayTitle
useLiturgicalTitle = true
}
}
}
.padding(11)
.background(RoundedRectangle(cornerRadius: 10).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.8))
}
FormSection(title: "Bezeichnung & Dienste") {
LabeledField(label: "Titel") {
TextField("z. B. Christmette", text: $title)
.textFieldStyle(.roundedBorder)
}
HStack(spacing: 26) {
HStack(spacing: 8) {
RoleBadge(role: .lector)
Stepper(value: $lectorsNeeded, in: 0...4) {
Text("\(lectorsNeeded)")
.font(.system(size: 12, weight: .semibold, design: .rounded))
.monospacedDigit()
}
.fixedSize()
}
HStack(spacing: 8) {
RoleBadge(role: .helper)
Stepper(value: $helpersNeeded, in: 0...4) {
Text("\(helpersNeeded)")
.font(.system(size: 12, weight: .semibold, design: .rounded))
.monospacedDigit()
}
.fixedSize()
}
Spacer()
}
}
FormSection(title: "Notizen") {
TextEditor(text: $notes)
.font(.system(size: 11))
.frame(height: 58)
.padding(5)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.card))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.8), lineWidth: 1))
}
}
.padding(22)
}
SheetFooter {
Spacer()
SecondaryActionButton(title: "Abbrechen", icon: "xmark") { dismiss() }
PrimaryActionButton(title: "Speichern", icon: "checkmark", action: save, disabled: !isValid)
}
}
.sheetSurface(width: 600, height: 610)
.onAppear(perform: load)
}
private func load() {
existing = request.service
if let service = existing {
churchID = service.churchID
date = service.date
timeDate = calendarTime(minutes: service.timeMinutes)
title = service.title
lectorsNeeded = service.lectorsNeeded
helpersNeeded = service.helpersNeeded
notes = service.notes
return
}
churchID = request.churchID ?? model.churches.first?.id ?? ""
date = request.date
timeDate = calendarTime(minutes: 18 * 60)
if let day = liturgicalDay {
title = day.isFeast ? day.displayTitle : ""
}
}
private func calendarTime(minutes: Int) -> Date {
let start = DayMath.today()
return DayMath.calendar.date(bySettingHour: minutes / 60, minute: minutes % 60, second: 0, of: start) ?? start
}
private func save() {
let comps = DayMath.calendar.dateComponents([.hour, .minute], from: timeDate)
let minutes = (comps.hour ?? 18) * 60 + (comps.minute ?? 0)
let service = ServiceOccurrence(
id: existing?.id ?? UUID().uuidString,
churchID: churchID,
templateID: nil,
date: date,
timeMinutes: minutes,
title: title.trimmingCharacters(in: .whitespaces),
lectorsNeeded: lectorsNeeded,
helpersNeeded: helpersNeeded,
kind: .special,
notes: notes.trimmingCharacters(in: .whitespacesAndNewlines),
locked: existing?.locked ?? false,
createdAt: existing?.createdAt ?? Date()
)
model.saveSpecialService(service)
dismiss()
}
}
@@ -0,0 +1,489 @@
import SwiftUI
import Charts
import LektorenPlanCore
struct StatisticsView: View {
@EnvironmentObject private var model: PlanModel
private var stats: RangeStatistics { model.stats }
private var topPeople: [PersonStat] {
Array(stats.personStats.sorted { $0.total > $1.total }.prefix(18))
}
private var monthlyPoints: [MonthlyPoint] {
var points: [MonthlyPoint] = []
var cursor = DayMath.startOfMonth(model.range.start)
let lastMonth = DayMath.startOfMonth(model.range.end)
while cursor <= lastMonth {
let key = DayMath.monthKey(cursor)
points.append(MonthlyPoint(
month: cursor,
label: "\(DayMath.shortMonthName(cursor)) \(String(DayMath.year(cursor)).suffix(2))",
count: stats.monthlyCounts[key] ?? 0
))
cursor = DayMath.adding(months: 1, to: cursor)
}
return points
}
private var monthlyBarWidth: MarkDimension {
monthlyPoints.count > 16 ? .automatic : .fixed(26)
}
private var activePersonStats: [PersonStat] {
stats.personStats.filter { $0.total > 0 }
}
var body: some View {
VStack(spacing: 14) {
PageHeader(
eyebrow: "Auswertung",
title: "Statistik & Verteilung",
subtitle: "Einsatzhäufigkeit, Orte, Vorlieben und Fairness für den gewählten Zeitraum."
) {
HStack(spacing: 8) {
SecondaryActionButton(title: "PDF", icon: "doc.richtext") {
model.createPDFPreview()
}
PrimaryActionButton(title: "Offene Dienste besetzen", icon: "wand.and.stars") {
_ = model.autoPlan(replaceExisting: false)
}
}
}
TimelineRangePicker()
ScrollView {
VStack(alignment: .leading, spacing: 14) {
kpiGrid
HStack(alignment: .top, spacing: 14) {
workloadChart
fairnessCard
.frame(width: 268)
}
monthlyChart
HStack(alignment: .top, spacing: 14) {
churchDistribution
preferenceCard
.frame(width: 300)
}
personTable
}
.padding(.bottom, 16)
}
}
.padding(.horizontal, 22)
.padding(.top, 30)
.padding(.bottom, 18)
}
// MARK: - KPI
private var kpiGrid: some View {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 156), spacing: 12)], spacing: 12) {
kpiCard(icon: "building.columns", value: "\(stats.serviceCount)", label: "Gottesdienste", tint: LP.accent)
kpiCard(icon: "checkmark.seal", value: "\(stats.assignmentCount)", label: "Einsätze", tint: LP.success)
kpiCard(icon: "circle.dashed", value: "\(stats.openSlots)", label: "offene Dienste", tint: LP.open)
kpiCard(icon: "percent", value: "\(Int(stats.coverageRate * 100)) %", label: "Besetzungsquote", tint: LP.gold)
kpiCard(icon: "star", value: "\(Int(stats.preferenceRate * 100)) %", label: "Präferenztreffer", tint: LP.burgundy)
kpiCard(icon: "person.2", value: "\(stats.activePeople)", label: "eingesetzte Personen", tint: LP.accent)
kpiCard(icon: "calendar.badge.minus", value: "\(stats.absenceDays)", label: "Abwesenheitstage", tint: LP.open)
kpiCard(icon: "cross.case", value: "\(stats.sundayServiceCount)", label: "Sonntage", tint: LP.gold)
}
}
private func kpiCard(icon: String, value: String, label: String, tint: Color) -> some View {
HStack(spacing: 9) {
Image(systemName: icon)
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(tint)
.frame(width: 30, height: 30)
.background(Circle().fill(tint.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text(value)
.font(.system(size: 17, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
.monospacedDigit()
Text(label)
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.lineLimit(1)
}
Spacer(minLength: 0)
}
.padding(10)
.background(RoundedRectangle(cornerRadius: 11).fill(LP.card))
.overlay(RoundedRectangle(cornerRadius: 11).strokeBorder(LP.line.opacity(0.55), lineWidth: 0.8))
}
// MARK: - Workload
private var workloadChart: some View {
SurfaceCard(padding: 16, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
chartHeader(
title: "Einsätze pro Person",
subtitle: "Top \(topPeople.count) im Zeitraum · faire Verteilung anstreben",
icon: "person.3"
)
if topPeople.allSatisfy({ $0.total == 0 }) || topPeople.isEmpty {
chartEmpty("Für diesen Zeitraum liegen noch keine Einsätze vor.")
} else {
Chart(topPeople) { stat in
BarMark(
x: .value("Einsätze", stat.total),
y: .value("Person", stat.person.lastName),
height: .fixed(8)
)
.foregroundStyle(
LinearGradient(colors: [LP.accent.opacity(0.85), LP.accent.opacity(0.5)],
startPoint: .leading, endPoint: .trailing)
)
.cornerRadius(3)
.annotation(position: .trailing, alignment: .leading) {
Text("\(stat.total)")
.font(.system(size: 8.5, weight: .semibold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
}
}
.chartXAxis {
AxisMarks(position: .bottom) { _ in
AxisGridLine().foregroundStyle(LP.line.opacity(0.4))
AxisValueLabel().foregroundStyle(LP.inkTertiary)
}
}
.chartYAxis {
AxisMarks { _ in
AxisValueLabel().foregroundStyle(LP.inkSecondary)
}
}
.frame(height: CGFloat(max(220, topPeople.count * 17)))
}
}
}
}
private var fairnessCard: some View {
let totals = activePersonStats.map(\.total)
let average = totals.isEmpty ? 0 : Double(totals.reduce(0, +)) / Double(totals.count)
let maximum = totals.max() ?? 0
let minimum = totals.min() ?? 0
return SurfaceCard(padding: 16, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
chartHeader(title: "Fairness", subtitle: "Verteilung der Last", icon: "scale.3d")
Text(String(format: "%.1f", average))
.font(.system(size: 30, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
Text("Einsätze pro aktive Person im Schnitt")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
Hairline()
fairnessRow(label: "Höchste Last", value: "\(maximum)")
fairnessRow(label: "Niedrigste Last", value: "\(minimum)")
fairnessRow(label: "Spannweite", value: "\(maximum - minimum)")
fairnessRow(label: "Aktive Personen", value: "\(totals.count)")
Hairline()
Text("Eine geringe Spannweite bedeutet eine gleichmäßige Verteilung. Präferenzen und Abwesenheiten können bewusst zu Abweichungen führen.")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
private func fairnessRow(label: String, value: String) -> some View {
HStack {
Text(label)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
Spacer()
Text(value)
.font(.system(size: 10.5, weight: .semibold, design: .rounded))
.foregroundStyle(LP.ink)
.monospacedDigit()
}
}
// MARK: - Monthly
private var monthlyChart: some View {
SurfaceCard(padding: 16, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
chartHeader(
title: "Verlauf nach Monat",
subtitle: "Einsätze im gewählten Zeitraum",
icon: "chart.bar.xaxis"
)
if monthlyPoints.isEmpty {
chartEmpty("Keine Monatsdaten im Zeitraum.")
} else {
Chart {
ForEach(monthlyPoints) { point in
BarMark(
x: .value("Monat", point.label),
y: .value("Einsätze", point.count),
width: monthlyBarWidth
)
.foregroundStyle(LP.accent.opacity(0.32))
.cornerRadius(3)
}
ForEach(monthlyPoints) { point in
LineMark(
x: .value("Monat", point.label),
y: .value("Einsätze", point.count)
)
.foregroundStyle(LP.gold)
.symbol(Circle())
.symbolSize(18)
.interpolationMethod(.catmullRom)
}
}
.chartYAxis {
AxisMarks { _ in
AxisGridLine().foregroundStyle(LP.line.opacity(0.4))
AxisValueLabel().foregroundStyle(LP.inkTertiary)
}
}
.chartXAxis {
AxisMarks { _ in
AxisValueLabel().foregroundStyle(LP.inkTertiary)
}
}
.frame(height: 168)
}
}
}
}
// MARK: - Church distribution
private var churchDistribution: some View {
SurfaceCard(padding: 16, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
chartHeader(
title: "Verteilung auf die Kirchen",
subtitle: "Einsätze, Gottesdienste und offene Dienste",
icon: "building.columns"
)
let maximum = max(1, stats.churchStats.map(\.assignments).max() ?? 1)
ForEach(stats.churchStats) { stat in
HStack(spacing: 10) {
ZStack {
RoundedRectangle(cornerRadius: 7).fill(LP.churchColor(stat.church.colorHex).opacity(0.10))
ChurchGlyph(symbol: stat.church.symbol, tint: LP.churchColor(stat.church.colorHex), lineWidth: 1.4, showGround: false)
.padding(4)
}
.frame(width: 32, height: 32)
VStack(alignment: .leading, spacing: 4) {
HStack {
Text(stat.church.name)
.font(.system(size: 10.5, weight: .semibold))
.foregroundStyle(LP.ink)
Spacer()
Text("\(stat.assignments) Einsätze · \(stat.services) Gottesdienste")
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
}
GeometryReader { geo in
ZStack(alignment: .leading) {
Capsule().fill(LP.line.opacity(0.35))
Capsule()
.fill(LP.churchColor(stat.church.colorHex))
.frame(width: max(3, geo.size.width * CGFloat(stat.assignments) / CGFloat(maximum)))
}
}
.frame(height: 6)
HStack(spacing: 8) {
Text("\(stat.personCount) Personen")
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
if stat.openSlots > 0 {
Text("\(stat.openSlots) offen")
.font(.system(size: 8, weight: .semibold))
.foregroundStyle(LP.open)
}
}
}
}
.padding(.vertical, 3)
}
}
}
}
// MARK: - Preferences
private var preferenceCard: some View {
SurfaceCard(padding: 16, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
chartHeader(title: "Vorlieben", subtitle: "Berücksichtigung im Plan", icon: "star")
ZStack {
Circle()
.stroke(LP.line.opacity(0.35), lineWidth: 9)
Circle()
.trim(from: 0, to: min(1, max(0, stats.preferenceRate)))
.stroke(
AngularGradient(colors: [LP.gold, LP.accent], center: .center),
style: StrokeStyle(lineWidth: 9, lineCap: .round)
)
.rotationEffect(.degrees(-90))
VStack(spacing: 1) {
Text("\(Int(stats.preferenceRate * 100))%")
.font(.system(size: 22, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
Text("Treffer")
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
}
}
.frame(width: 112, height: 112)
.frame(maxWidth: .infinity)
fairnessRow(label: "Treffer", value: "\(stats.preferenceHits)")
fairnessRow(label: "Bewertbare Einsätze", value: "\(stats.preferenceEligible)")
Text("Gezählt werden Einsätze, bei denen Kirche, Wochentag oder Gottesdienst einer hinterlegten Präferenz entsprechen.")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
// MARK: - Person table
private var personTable: some View {
SurfaceCard(padding: 0, radius: 15, background: LP.card) {
VStack(spacing: 0) {
HStack {
Text("EINSATZÜBERSICHT")
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(1.1)
.foregroundStyle(LP.inkTertiary)
Spacer()
Text("Personen mit Einsätzen im Zeitraum")
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
}
.padding(.horizontal, 14)
.padding(.vertical, 11)
Hairline()
HStack(spacing: 8) {
Text("Person")
.frame(maxWidth: .infinity, alignment: .leading)
Text("L")
.frame(width: 28)
Text("K")
.frame(width: 28)
Text("Sonntage")
.frame(width: 62)
Text("Kirchen")
.frame(width: 150, alignment: .leading)
Text("Präferenz")
.frame(width: 70)
Text("Zuletzt")
.frame(width: 86, alignment: .leading)
}
.font(.system(size: 8, weight: .bold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
.padding(.horizontal, 14)
.padding(.vertical, 7)
.background(LP.cardMuted.opacity(0.5))
ForEach(Array(activePersonStats.enumerated()), id: \.element.id) { index, stat in
HStack(spacing: 8) {
HStack(spacing: 6) {
Avatar(initials: stat.person.initials,
color: stat.person.roles.contains(.lector) ? LP.accent : LP.burgundy,
size: 20)
Text(stat.person.fullName)
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
.lineLimit(1)
}
.frame(maxWidth: .infinity, alignment: .leading)
Text("\(stat.lectors)")
.frame(width: 28)
Text("\(stat.helpers)")
.frame(width: 28)
Text("\(stat.sundayCount)")
.frame(width: 62)
HStack(spacing: 3) {
ForEach(Array(stat.churchCounts.sorted { $0.value > $1.value }.prefix(3)), id: \.key) { item in
if let church = model.churchByID[item.key] {
Text("\(church.shortName) \(item.value)")
.font(.system(size: 8))
.foregroundStyle(LP.churchColor(church.colorHex))
.lineLimit(1)
.fixedSize(horizontal: true, vertical: false)
.padding(.horizontal, 4)
.padding(.vertical, 1)
.background(Capsule().fill(LP.churchColor(church.colorHex).opacity(0.08)))
}
}
}
.frame(width: 150, alignment: .leading)
Text(StatisticsCalculator.hasAnyPreference(stat.person)
? "\(Int(stat.preferenceRate * 100)) %"
: "—")
.frame(width: 70)
.foregroundStyle(stat.preferenceRate >= 0.6 ? LP.success : LP.inkSecondary)
Text(stat.lastAssignment.map(DayMath.mediumString) ?? "—")
.frame(width: 86, alignment: .leading)
.foregroundStyle(LP.inkTertiary)
}
.font(.system(size: 9.5, design: .rounded))
.foregroundStyle(LP.inkSecondary)
.padding(.horizontal, 14)
.padding(.vertical, 5)
.background(index % 2 == 0 ? LP.cardMuted.opacity(0.22) : Color.clear)
}
}
}
}
// MARK: - Helpers
private func chartHeader(title: String, subtitle: String, icon: String) -> some View {
HStack(alignment: .top, spacing: 8) {
Image(systemName: icon)
.font(.system(size: 10.5, weight: .semibold))
.foregroundStyle(LP.accent)
.padding(.top, 1)
VStack(alignment: .leading, spacing: 1) {
Text(title)
.font(LP.serifSubhead)
.foregroundStyle(LP.ink)
Text(subtitle)
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
}
Spacer()
}
}
private func chartEmpty(_ message: String) -> some View {
Text(message)
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
.frame(maxWidth: .infinity, minHeight: 130)
}
}
private struct MonthlyPoint: Identifiable {
var month: Date
var label: String
var count: Int
var id: String { label }
}
+255
View File
@@ -0,0 +1,255 @@
import SwiftUI
import LektorenPlanCore
private enum TeamFilter: String, CaseIterable, Identifiable {
case all, lectors, helpers, inactive
var id: String { rawValue }
var title: String {
switch self {
case .all: "Alle"
case .lectors: "Lektoren"
case .helpers: "Kommunionhelfer"
case .inactive: "Inaktiv"
}
}
}
struct TeamView: View {
@EnvironmentObject private var model: PlanModel
@State private var filter: TeamFilter = .all
@State private var search = ""
private let columns = [GridItem(.adaptive(minimum: 292), spacing: 12)]
private var filteredPeople: [Person] {
let query = search.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return model.people.filter { person in
switch filter {
case .all:
if !person.active { return false }
case .lectors:
if !person.active || !person.roles.contains(.lector) { return false }
case .helpers:
if !person.active || !person.roles.contains(.helper) { return false }
case .inactive:
if person.active { return false }
}
guard !query.isEmpty else { return true }
if person.fullName.lowercased().contains(query) { return true }
if person.email.lowercased().contains(query) { return true }
if person.roleLabel.lowercased().contains(query) { return true }
return false
}
}
var body: some View {
VStack(spacing: 14) {
PageHeader(
eyebrow: "Lektoren & Kommunionhelfer",
title: "Das Team",
subtitle: "Rollen, bevorzugte Orte, Einsatztage, Abwesenheiten und Monatslimits."
) {
HStack(spacing: 8) {
SecondaryActionButton(title: "Abwesenheiten", icon: "calendar.badge.minus") {}
.hidden()
PrimaryActionButton(title: "Person hinzufügen", icon: "person.badge.plus") {
model.personEditor = PersonEditorRequest(person: nil)
}
}
}
summaryBar
filterBar
ScrollView {
LazyVGrid(columns: columns, alignment: .leading, spacing: 12) {
ForEach(filteredPeople) { person in
personCard(person)
}
}
.padding(.bottom, 16)
}
}
.padding(.horizontal, 22)
.padding(.top, 30)
.padding(.bottom, 18)
}
private var summaryBar: some View {
SurfaceCard(padding: 13, radius: 14, background: LP.card.opacity(0.9)) {
HStack(spacing: 0) {
StatPill(icon: "person.2", value: "\(model.people.filter(\.active).count)", label: "Aktiv")
divider
StatPill(icon: "book.closed", value: "\(model.lectorCount)", label: "Lektoren", tint: LP.accent)
divider
StatPill(icon: "hand.raised", value: "\(model.helperCount)", label: "Kommunionhelfer", tint: LP.burgundy)
divider
StatPill(icon: "calendar.badge.minus", value: "\(model.absences.count)", label: "Abwesenheiten", tint: LP.open)
divider
StatPill(icon: "checkmark.seal", value: "\(model.stats.activePeople)", label: "im Zeitraum eingeteilt", tint: LP.success)
Spacer()
}
}
}
private var divider: some View {
Rectangle()
.fill(LP.line.opacity(0.55))
.frame(width: 1, height: 28)
.padding(.horizontal, 12)
}
private var filterBar: some View {
HStack(spacing: 12) {
HStack(spacing: 2) {
ForEach(TeamFilter.allCases) { item in
Button {
withAnimation(.easeInOut(duration: 0.15)) { filter = item }
} label: {
Text(item.title)
.font(.system(size: 10.5, weight: .semibold))
.foregroundStyle(filter == item ? .white : LP.inkSecondary)
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(Capsule().fill(filter == item ? LP.accent : Color.clear))
}
.buttonStyle(.plain)
}
}
.padding(3)
.background(Capsule().fill(LP.cardMuted))
.overlay(Capsule().strokeBorder(LP.line.opacity(0.55), lineWidth: 0.7))
HStack(spacing: 5) {
Image(systemName: "magnifyingglass")
.font(.system(size: 10))
.foregroundStyle(LP.inkTertiary)
TextField("Person suchen…", text: $search)
.textFieldStyle(.plain)
.font(.system(size: 10.5))
.frame(width: 160)
}
.padding(.horizontal, 8)
.padding(.vertical, 5)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.7))
Spacer()
Text("\(filteredPeople.count) Personen")
.font(.system(size: 9.5, weight: .medium, design: .rounded))
.foregroundStyle(LP.inkTertiary)
}
}
private func personCard(_ person: Person) -> some View {
let assignments = model.assignmentCount(for: person.id)
let currentAbsence = model.currentAbsence(for: person)
let roleColor = person.roles.contains(.lector) ? LP.accent : LP.burgundy
return Button {
model.personEditor = PersonEditorRequest(person: person)
} label: {
VStack(alignment: .leading, spacing: 9) {
HStack(spacing: 9) {
Avatar(initials: person.initials, color: roleColor, size: 34)
VStack(alignment: .leading, spacing: 2) {
Text(person.fullName)
.font(.system(size: 12.5, weight: .semibold))
.foregroundStyle(LP.ink)
HStack(spacing: 4) {
ForEach(Role.allCases.filter { person.roles.contains($0) }) { role in
TinyBadge(text: role.title.uppercased(), color: role == .lector ? LP.accent : LP.burgundy)
}
}
}
Spacer(minLength: 4)
VStack(alignment: .trailing, spacing: 1) {
Text("\(assignments)")
.font(.system(size: 16, weight: .bold, design: .rounded))
.foregroundStyle(assignments > 0 ? LP.ink : LP.inkTertiary)
Text("Einsätze")
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
}
}
if !person.notes.isEmpty {
Text(person.notes)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
.lineLimit(2)
.frame(maxWidth: .infinity, alignment: .leading)
}
VStack(alignment: .leading, spacing: 5) {
preferenceRow(
icon: "building.columns",
text: person.preferredChurchIDs.isEmpty
? "Alle Kirchen"
: person.preferredChurchIDs.compactMap { model.churchByID[$0]?.shortName }.sorted().joined(separator: ", "),
active: !person.preferredChurchIDs.isEmpty
)
preferenceRow(
icon: "calendar",
text: person.preferredWeekdays.isEmpty
? "Alle Tage"
: person.preferredWeekdays.sorted().map(weekdayShort).joined(separator: ", "),
active: !person.preferredWeekdays.isEmpty
)
if !person.preferredServiceTitles.isEmpty {
preferenceRow(
icon: "book.closed",
text: person.preferredServiceTitles.joined(separator: ", "),
active: true
)
}
}
HStack(spacing: 6) {
TinyBadge(text: "MAX \(person.maxPerMonth)×/MONAT", color: LP.inkTertiary)
if let currentAbsence {
TinyBadge(text: "ABWESEND · \(currentAbsence.reason.isEmpty ? "bis \(DayMath.mediumString(currentAbsence.end))" : currentAbsence.reason)", color: LP.open, filled: true)
} else if !model.absences(for: person.id).isEmpty {
TinyBadge(text: "\(model.absences(for: person.id).count)× ABWESEND", color: LP.inkTertiary)
}
Spacer()
Image(systemName: "chevron.right")
.font(.system(size: 8, weight: .semibold))
.foregroundStyle(LP.inkTertiary.opacity(0.6))
}
}
.padding(13)
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 14, style: .continuous)
.fill(LP.card)
.shadow(color: .black.opacity(0.03), radius: 8, y: 3)
)
.overlay(
RoundedRectangle(cornerRadius: 14, style: .continuous)
.strokeBorder(LP.line.opacity(0.55), lineWidth: 1)
)
.opacity(person.active ? 1 : 0.62)
}
.buttonStyle(.plain)
.help("\(person.fullName)\n\(person.roleLabel)\nKlicken zum Bearbeiten")
}
private func preferenceRow(icon: String, text: String, active: Bool) -> some View {
HStack(spacing: 5) {
Image(systemName: icon)
.font(.system(size: 8))
.foregroundStyle(active ? LP.accent : LP.inkTertiary)
.frame(width: 11)
Text(text)
.font(.system(size: 9))
.foregroundStyle(active ? LP.inkSecondary : LP.inkTertiary)
.lineLimit(1)
}
}
private func weekdayShort(_ weekday: Int) -> String {
["", "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"][max(0, min(7, weekday))]
}
}
@@ -0,0 +1,231 @@
import SwiftUI
import LektorenPlanCore
struct TemplateEditorSheet: View {
@EnvironmentObject private var model: PlanModel
@Environment(\.dismiss) private var dismiss
let request: TemplateEditorRequest
@State private var churchID = ""
@State private var weekday = 1
@State private var timeDate = Date()
@State private var title = ""
@State private var lectorsNeeded = 1
@State private var helpersNeeded = 1
@State private var validFrom = DayMath.today()
@State private var hasValidTo = false
@State private var validTo = DayMath.adding(years: 1, to: DayMath.today())
@State private var active = true
@State private var notes = ""
@State private var confirmDelete = false
private var isEditing: Bool { request.template != nil }
private var isValid: Bool {
!churchID.isEmpty && !title.trimmingCharacters(in: .whitespaces).isEmpty
&& (lectorsNeeded + helpersNeeded) > 0
}
private var weekdayOptions: [(Int, String)] {
[(1, "Sonntag"), (2, "Montag"), (3, "Dienstag"), (4, "Mittwoch"),
(5, "Donnerstag"), (6, "Freitag"), (7, "Samstag")]
}
var body: some View {
VStack(spacing: 0) {
SheetHeader(
icon: "building.columns",
title: isEditing ? "Gottesdienst bearbeiten" : "Neuer regelmäßiger Gottesdienst",
subtitle: "Wiederkehrender Termin der Gottesdienstordnung inklusive benötigter Dienste."
)
Hairline()
ScrollView {
VStack(alignment: .leading, spacing: 22) {
FormSection(title: "Ort & Zeit") {
HStack(spacing: 12) {
LabeledField(label: "Kirche") {
Picker("", selection: $churchID) {
ForEach(model.churches) { church in
Text(church.name).tag(church.id)
}
}
.labelsHidden()
.pickerStyle(.menu)
}
LabeledField(label: "Wochentag") {
Picker("", selection: $weekday) {
ForEach(weekdayOptions, id: \.0) { option in
Text(option.1).tag(option.0)
}
}
.labelsHidden()
.pickerStyle(.menu)
}
LabeledField(label: "Uhrzeit") {
DatePicker("", selection: $timeDate, displayedComponents: .hourAndMinute)
.labelsHidden()
.datePickerStyle(.field)
}
}
LabeledField(label: "Bezeichnung") {
TextField("z. B. Hochamt, Vorabendmesse, Wort-Gottes-Feier", text: $title)
.textFieldStyle(.roundedBorder)
}
}
FormSection(
title: "Benötigte Dienste",
subtitle: "Wie viele Personen werden pro Termin eingeplant?"
) {
HStack(spacing: 26) {
HStack(spacing: 8) {
RoleBadge(role: .lector)
Stepper(value: $lectorsNeeded, in: 0...4) {
Text("\(lectorsNeeded)")
.font(.system(size: 12, weight: .semibold, design: .rounded))
.monospacedDigit()
}
.fixedSize()
}
HStack(spacing: 8) {
RoleBadge(role: .helper)
Stepper(value: $helpersNeeded, in: 0...4) {
Text("\(helpersNeeded)")
.font(.system(size: 12, weight: .semibold, design: .rounded))
.monospacedDigit()
}
.fixedSize()
}
Spacer()
}
}
FormSection(title: "Gültigkeit") {
HStack(spacing: 12) {
LabeledField(label: "Gültig ab") {
DatePicker("", selection: $validFrom, displayedComponents: .date)
.labelsHidden()
.datePickerStyle(.field)
}
Toggle(isOn: $hasValidTo) {
Text("Befristet")
.font(.system(size: 10.5, weight: .medium))
}
.toggleStyle(.checkbox)
if hasValidTo {
LabeledField(label: "Gültig bis") {
DatePicker("", selection: $validTo, displayedComponents: .date)
.labelsHidden()
.datePickerStyle(.field)
}
}
Spacer()
}
Toggle(isOn: $active) {
Text("Vorlage aktiv – Termine werden bei der Erzeugung berücksichtigt")
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.inkSecondary)
}
.toggleStyle(.checkbox)
}
FormSection(title: "Notizen") {
TextEditor(text: $notes)
.font(.system(size: 11))
.frame(height: 58)
.padding(5)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.card))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.8), lineWidth: 1))
}
}
.padding(22)
}
SheetFooter {
if isEditing {
Button {
confirmDelete = true
} label: {
HStack(spacing: 5) {
Image(systemName: "trash")
Text("Vorlage löschen")
}
.font(.system(size: 11.5, weight: .medium))
.foregroundStyle(LP.danger)
}
.buttonStyle(.plain)
}
Spacer()
SecondaryActionButton(title: "Abbrechen", icon: "xmark") { dismiss() }
PrimaryActionButton(title: "Speichern", icon: "checkmark", action: save, disabled: !isValid)
}
}
.sheetSurface(width: 620, height: 620)
.onAppear(perform: load)
.confirmationDialog(
"Vorlage löschen?",
isPresented: $confirmDelete,
titleVisibility: .visible
) {
Button("Vorlage löschen", role: .destructive) {
if let template = request.template {
model.deleteTemplate(template)
}
dismiss()
}
Button("Abbrechen", role: .cancel) {}
} message: {
Text("Bereits erzeugte Termine bleiben erhalten. Künftige Termine dieser Vorlage entfallen.")
}
}
private func load() {
churchID = request.template?.churchID ?? request.churchID ?? model.churches.first?.id ?? ""
guard let template = request.template else {
weekday = DayMath.weekday(DayMath.today())
timeDate = timeDateFor(minutes: 9 * 60 + 30)
title = "Hochamt"
return
}
weekday = template.weekday
timeDate = timeDateFor(minutes: template.timeMinutes)
title = template.title
lectorsNeeded = template.lectorsNeeded
helpersNeeded = template.helpersNeeded
validFrom = template.validFrom
if let end = template.validTo {
hasValidTo = true
validTo = end
}
active = template.active
notes = template.notes
}
private func timeDateFor(minutes: Int) -> Date {
let start = DayMath.today()
return DayMath.calendar.date(bySettingHour: minutes / 60, minute: minutes % 60, second: 0, of: start) ?? start
}
private func save() {
let comps = DayMath.calendar.dateComponents([.hour, .minute], from: timeDate)
let minutes = (comps.hour ?? 9) * 60 + (comps.minute ?? 30)
let template = ServiceTemplate(
id: request.template?.id ?? UUID().uuidString,
churchID: churchID,
weekday: weekday,
timeMinutes: minutes,
title: title.trimmingCharacters(in: .whitespaces),
lectorsNeeded: lectorsNeeded,
helpersNeeded: helpersNeeded,
validFrom: validFrom,
validTo: hasValidTo ? validTo : nil,
active: active,
notes: notes.trimmingCharacters(in: .whitespacesAndNewlines)
)
model.saveTemplate(template)
dismiss()
}
}
+756
View File
@@ -0,0 +1,756 @@
import Foundation
public final class AppDatabase {
public let database: SQLiteDatabase
public let path: String
private let encoder = JSONEncoder()
private let decoder = JSONDecoder()
public init(path: String, seedDemo: Bool = true) throws {
self.path = path
self.database = try SQLiteDatabase(path: path)
try migrate()
if seedDemo, try churchCount() == 0 {
try DemoData.seed(into: self)
}
}
public static func defaultPath() -> String {
let fm = FileManager.default
let base = fm.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
?? fm.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support")
let folder = base.appendingPathComponent("LektorenPlan", isDirectory: true)
try? fm.createDirectory(at: folder, withIntermediateDirectories: true)
return folder.appendingPathComponent("lektorenplan.sqlite").path
}
public static func makeInMemory(seedDemo: Bool = false) throws -> AppDatabase {
try AppDatabase(path: ":memory:", seedDemo: seedDemo)
}
private func migrate() throws {
let schema = """
CREATE TABLE IF NOT EXISTS churches (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
short_name TEXT NOT NULL,
symbol TEXT NOT NULL,
color_hex TEXT NOT NULL,
address TEXT NOT NULL DEFAULT '',
sort_index INTEGER NOT NULL DEFAULT 0,
notes TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS people (
id TEXT PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
roles TEXT NOT NULL,
email TEXT NOT NULL DEFAULT '',
phone TEXT NOT NULL DEFAULT '',
preferred_church_ids TEXT NOT NULL DEFAULT '[]',
preferred_weekdays TEXT NOT NULL DEFAULT '[]',
preferred_service_titles TEXT NOT NULL DEFAULT '[]',
max_per_month INTEGER NOT NULL DEFAULT 6,
active INTEGER NOT NULL DEFAULT 1,
notes TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS absences (
id TEXT PRIMARY KEY,
person_id TEXT NOT NULL REFERENCES people(id) ON DELETE CASCADE,
start_date TEXT NOT NULL,
end_date TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_absences_person ON absences(person_id);
CREATE TABLE IF NOT EXISTS service_templates (
id TEXT PRIMARY KEY,
church_id TEXT NOT NULL REFERENCES churches(id) ON DELETE CASCADE,
weekday INTEGER NOT NULL,
time_minutes INTEGER NOT NULL,
title TEXT NOT NULL,
lectors_needed INTEGER NOT NULL DEFAULT 1,
helpers_needed INTEGER NOT NULL DEFAULT 1,
valid_from TEXT NOT NULL,
valid_to TEXT,
active INTEGER NOT NULL DEFAULT 1,
notes TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_templates_church ON service_templates(church_id);
CREATE TABLE IF NOT EXISTS service_exceptions (
id TEXT PRIMARY KEY,
template_id TEXT NOT NULL REFERENCES service_templates(id) ON DELETE CASCADE,
date TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
UNIQUE(template_id, date)
);
CREATE TABLE IF NOT EXISTS services (
id TEXT PRIMARY KEY,
church_id TEXT NOT NULL REFERENCES churches(id) ON DELETE CASCADE,
template_id TEXT REFERENCES service_templates(id) ON DELETE SET NULL,
date TEXT NOT NULL,
time_minutes INTEGER NOT NULL,
title TEXT NOT NULL,
lectors_needed INTEGER NOT NULL DEFAULT 1,
helpers_needed INTEGER NOT NULL DEFAULT 1,
kind TEXT NOT NULL DEFAULT 'regular',
notes TEXT NOT NULL DEFAULT '',
locked INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_services_date ON services(date);
CREATE INDEX IF NOT EXISTS idx_services_church ON services(church_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_services_template_date
ON services(template_id, date) WHERE template_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS assignments (
id TEXT PRIMARY KEY,
service_id TEXT NOT NULL REFERENCES services(id) ON DELETE CASCADE,
person_id TEXT NOT NULL REFERENCES people(id) ON DELETE CASCADE,
role TEXT NOT NULL,
locked INTEGER NOT NULL DEFAULT 0,
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
UNIQUE(service_id, person_id, role)
);
CREATE INDEX IF NOT EXISTS idx_assignments_service ON assignments(service_id);
CREATE INDEX IF NOT EXISTS idx_assignments_person ON assignments(person_id);
CREATE TABLE IF NOT EXISTS liturgical_days (
date TEXT PRIMARY KEY,
title TEXT NOT NULL,
rank TEXT NOT NULL DEFAULT '',
color TEXT NOT NULL DEFAULT 'g',
remark TEXT NOT NULL DEFAULT '',
first_reading TEXT NOT NULL DEFAULT '',
psalm TEXT NOT NULL DEFAULT '',
second_reading TEXT NOT NULL DEFAULT '',
gospel TEXT NOT NULL DEFAULT '',
is_obligation INTEGER NOT NULL DEFAULT 0,
source TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_liturgical_date ON liturgical_days(date);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
"""
try database.execute(schema)
try database.run("INSERT OR IGNORE INTO settings(key, value) VALUES('schemaVersion', '1')")
}
// MARK: - Churches
public func churchCount() throws -> Int {
try database.scalarInt("SELECT COUNT(*) AS value FROM churches")
}
public func churches() throws -> [Church] {
try database.query("SELECT * FROM churches ORDER BY sort_index, name").compactMap { row in
guard let id = row.string("id"),
let name = row.string("name"),
let shortName = row.string("short_name"),
let symbolRaw = row.string("symbol")
else { return nil }
return Church(
id: id,
name: name,
shortName: shortName,
symbol: ChurchSymbol(rawValue: symbolRaw) ?? .chapel,
colorHex: row.string("color_hex", default: "#2F5D62"),
address: row.string("address", default: ""),
sortIndex: row.int("sort_index", default: 0),
notes: row.string("notes", default: "")
)
}
}
public func upsert(_ church: Church) throws {
try database.run("""
INSERT INTO churches(id, name, short_name, symbol, color_hex, address, sort_index, notes)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
name=excluded.name, short_name=excluded.short_name, symbol=excluded.symbol,
color_hex=excluded.color_hex, address=excluded.address,
sort_index=excluded.sort_index, notes=excluded.notes
""", [
.text(church.id), .text(church.name), .text(church.shortName),
.text(church.symbol.rawValue), .text(church.colorHex), .text(church.address),
.int(church.sortIndex), .text(church.notes)
])
}
public func deleteChurch(id: String) throws {
try database.run("DELETE FROM churches WHERE id=?", [.text(id)])
}
// MARK: - People
public func people() throws -> [Person] {
try database.query("SELECT * FROM people ORDER BY last_name, first_name").compactMap { decodePerson($0) }
}
public func person(id: String) throws -> Person? {
try database.query("SELECT * FROM people WHERE id=?", [.text(id)]).first.flatMap(decodePerson)
}
public func upsert(_ person: Person) throws {
let roles = encode(person.roles.map(\.rawValue).sorted())
let churches = encode(person.preferredChurchIDs.sorted())
let weekdays = encode(person.preferredWeekdays.sorted())
let titles = encode(person.preferredServiceTitles)
try database.run("""
INSERT INTO people(id, first_name, last_name, roles, email, phone, preferred_church_ids,
preferred_weekdays, preferred_service_titles, max_per_month, active, notes)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
first_name=excluded.first_name, last_name=excluded.last_name, roles=excluded.roles,
email=excluded.email, phone=excluded.phone,
preferred_church_ids=excluded.preferred_church_ids,
preferred_weekdays=excluded.preferred_weekdays,
preferred_service_titles=excluded.preferred_service_titles,
max_per_month=excluded.max_per_month, active=excluded.active, notes=excluded.notes
""", [
.text(person.id), .text(person.firstName), .text(person.lastName), .text(roles),
.text(person.email), .text(person.phone), .text(churches), .text(weekdays),
.text(titles), .int(person.maxPerMonth), .bool(person.active), .text(person.notes)
])
}
public func deletePerson(id: String) throws {
try database.run("DELETE FROM people WHERE id=?", [.text(id)])
}
private func decodePerson(_ row: SQLiteRow) -> Person? {
guard let id = row.string("id"),
let first = row.string("first_name"),
let last = row.string("last_name")
else { return nil }
let roleStrings: [String] = decode(row.string("roles", default: "[]"))
return Person(
id: id,
firstName: first,
lastName: last,
roles: Set(roleStrings.compactMap(Role.init(rawValue:))),
email: row.string("email", default: ""),
phone: row.string("phone", default: ""),
preferredChurchIDs: Set(decode(row.string("preferred_church_ids", default: "[]")) as [String]),
preferredWeekdays: Set(decode(row.string("preferred_weekdays", default: "[]")) as [Int]),
preferredServiceTitles: decode(row.string("preferred_service_titles", default: "[]")),
maxPerMonth: row.int("max_per_month", default: 6),
active: row.bool("active", default: true),
notes: row.string("notes", default: "")
)
}
// MARK: - Absences
public func absences() throws -> [Absence] {
try database.query("SELECT * FROM absences ORDER BY start_date").compactMap { row in
guard let id = row.string("id"), let personID = row.string("person_id"),
let start = row.date("start_date"), let end = row.date("end_date")
else { return nil }
return Absence(id: id, personID: personID, start: start, end: end, reason: row.string("reason", default: ""))
}
}
public func absences(personID: String) throws -> [Absence] {
try database.query("SELECT * FROM absences WHERE person_id=? ORDER BY start_date", [.text(personID)]).compactMap { row in
guard let id = row.string("id"), let start = row.date("start_date"), let end = row.date("end_date") else { return nil }
return Absence(id: id, personID: personID, start: start, end: end, reason: row.string("reason", default: ""))
}
}
public func upsert(_ absence: Absence) throws {
try database.run("""
INSERT INTO absences(id, person_id, start_date, end_date, reason) VALUES(?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET person_id=excluded.person_id, start_date=excluded.start_date,
end_date=excluded.end_date, reason=excluded.reason
""", [
.text(absence.id), .text(absence.personID), .dateKey(absence.start),
.dateKey(absence.end), .text(absence.reason)
])
}
public func deleteAbsence(id: String) throws {
try database.run("DELETE FROM absences WHERE id=?", [.text(id)])
}
// MARK: - Service templates
public func templates() throws -> [ServiceTemplate] {
try database.query("SELECT * FROM service_templates ORDER BY weekday, time_minutes").compactMap { row in
guard let id = row.string("id"), let churchID = row.string("church_id"),
let title = row.string("title"), let from = row.date("valid_from")
else { return nil }
return ServiceTemplate(
id: id,
churchID: churchID,
weekday: row.int("weekday", default: 1),
timeMinutes: row.int("time_minutes", default: 600),
title: title,
lectorsNeeded: row.int("lectors_needed", default: 1),
helpersNeeded: row.int("helpers_needed", default: 1),
validFrom: from,
validTo: row.date("valid_to"),
active: row.bool("active", default: true),
notes: row.string("notes", default: "")
)
}
}
public func upsert(_ template: ServiceTemplate) throws {
try database.run("""
INSERT INTO service_templates(id, church_id, weekday, time_minutes, title, lectors_needed,
helpers_needed, valid_from, valid_to, active, notes)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET church_id=excluded.church_id, weekday=excluded.weekday,
time_minutes=excluded.time_minutes, title=excluded.title,
lectors_needed=excluded.lectors_needed, helpers_needed=excluded.helpers_needed,
valid_from=excluded.valid_from, valid_to=excluded.valid_to,
active=excluded.active, notes=excluded.notes
""", [
.text(template.id), .text(template.churchID), .int(template.weekday),
.int(template.timeMinutes), .text(template.title), .int(template.lectorsNeeded),
.int(template.helpersNeeded), .dateKey(template.validFrom),
template.validTo.map(SQLiteValue.dateKey) ?? .null,
.bool(template.active), .text(template.notes)
])
}
public func deleteTemplate(id: String) throws {
try database.run("DELETE FROM service_templates WHERE id=?", [.text(id)])
}
// MARK: - Exceptions
public func exceptions() throws -> [ServiceException] {
try database.query("SELECT * FROM service_exceptions ORDER BY date").compactMap { row in
guard let id = row.string("id"), let templateID = row.string("template_id"), let date = row.date("date") else { return nil }
return ServiceException(id: id, templateID: templateID, date: date, reason: row.string("reason", default: ""))
}
}
public func upsert(_ exception: ServiceException) throws {
try database.run("""
INSERT INTO service_exceptions(id, template_id, date, reason) VALUES(?, ?, ?, ?)
ON CONFLICT(template_id, date) DO UPDATE SET reason=excluded.reason
""", [.text(exception.id), .text(exception.templateID), .dateKey(exception.date), .text(exception.reason)])
}
public func deleteException(id: String) throws {
try database.run("DELETE FROM service_exceptions WHERE id=?", [.text(id)])
}
// MARK: - Services
public func services(in range: DayRange) throws -> [ServiceOccurrence] {
try database.query("""
SELECT * FROM services WHERE date >= ? AND date <= ?
ORDER BY date, time_minutes, church_id
""", [.dateKey(range.start), .dateKey(range.end)]).compactMap(decodeService)
}
public func services(on date: Date) throws -> [ServiceOccurrence] {
try database.query("SELECT * FROM services WHERE date=? ORDER BY time_minutes", [.dateKey(date)]).compactMap(decodeService)
}
public func service(id: String) throws -> ServiceOccurrence? {
try database.query("SELECT * FROM services WHERE id=?", [.text(id)]).first.flatMap(decodeService)
}
public func specialServices() throws -> [ServiceOccurrence] {
try database.query("SELECT * FROM services WHERE kind='special' ORDER BY date, time_minutes").compactMap(decodeService)
}
public func serviceCount() throws -> Int {
try database.scalarInt("SELECT COUNT(*) AS value FROM services")
}
public func upsert(_ service: ServiceOccurrence) throws {
try database.run("""
INSERT INTO services(id, church_id, 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,
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,
.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))
])
}
public func deleteService(id: String) throws {
try database.run("DELETE FROM services WHERE id=?", [.text(id)])
}
private func decodeService(_ row: SQLiteRow) -> ServiceOccurrence? {
guard let id = row.string("id"), let churchID = row.string("church_id"),
let date = row.date("date"), let title = row.string("title")
else { return nil }
return ServiceOccurrence(
id: id,
churchID: churchID,
templateID: row.string("template_id"),
date: date,
timeMinutes: row.int("time_minutes", default: 600),
title: title,
lectorsNeeded: row.int("lectors_needed", default: 1),
helpersNeeded: row.int("helpers_needed", default: 1),
kind: ServiceKind(rawValue: row.string("kind", default: "regular")) ?? .regular,
notes: row.string("notes", default: ""),
locked: row.bool("locked", default: false),
createdAt: ISO8601DateFormatter().date(from: row.string("created_at", default: "")) ?? Date()
)
}
/// Generates regular occurrences from the current service order. Existing occurrences
/// that already have assignments are never overwritten.
@discardableResult
public func generateServices(in range: DayRange, regenerateUnassigned: Bool = true) throws -> Int {
let allTemplates = try templates()
let allExceptions = try exceptions()
let exceptionKeys = Set(allExceptions.map { "\($0.templateID)|\(DayMath.key($0.date))" })
let existing = try services(in: range)
var existingByTemplate: [String: ServiceOccurrence] = [:]
for service in existing {
if let templateID = service.templateID {
existingByTemplate["\(templateID)|\(service.dateKey)"] = service
}
}
var created = 0
try database.transaction {
for day in range.days {
for template in allTemplates where template.isValid(on: day) {
let key = "\(template.id)|\(DayMath.key(day))"
if exceptionKeys.contains(key) { continue }
if let existing = existingByTemplate[key] {
guard regenerateUnassigned else { continue }
let assignmentCount = try assignmentCount(serviceID: existing.id)
if assignmentCount == 0 {
var updated = existing
updated.timeMinutes = template.timeMinutes
updated.title = template.title
updated.lectorsNeeded = template.lectorsNeeded
updated.helpersNeeded = template.helpersNeeded
try upsert(updated)
}
continue
}
let service = ServiceOccurrence(
churchID: template.churchID,
templateID: template.id,
date: day,
timeMinutes: template.timeMinutes,
title: template.title,
lectorsNeeded: template.lectorsNeeded,
helpersNeeded: template.helpersNeeded,
kind: .regular,
notes: template.notes
)
try upsert(service)
created += 1
}
}
}
return created
}
private func assignmentCount(serviceID: String) throws -> Int {
try database.scalarInt("SELECT COUNT(*) AS value FROM assignments WHERE service_id=?", [.text(serviceID)])
}
// MARK: - Assignments
public func assignments(in range: DayRange) throws -> [Assignment] {
try database.query("""
SELECT a.* FROM assignments a JOIN services s ON s.id = a.service_id
WHERE s.date >= ? AND s.date <= ?
ORDER BY s.date, s.time_minutes
""", [.dateKey(range.start), .dateKey(range.end)]).compactMap(decodeAssignment)
}
public func assignments(serviceIDs: [String]) throws -> [Assignment] {
guard !serviceIDs.isEmpty else { return [] }
let placeholders = Array(repeating: "?", count: serviceIDs.count).joined(separator: ",")
return try database.query(
"SELECT * FROM assignments WHERE service_id IN (\(placeholders))",
serviceIDs.map(SQLiteValue.text)
).compactMap(decodeAssignment)
}
public func assignments(personID: String) throws -> [Assignment] {
try database.query("SELECT * FROM assignments WHERE person_id=?", [.text(personID)]).compactMap(decodeAssignment)
}
public func assignmentCount() throws -> Int {
try database.scalarInt("SELECT COUNT(*) AS value FROM assignments")
}
public func upsert(_ assignment: Assignment) throws {
try database.run("""
INSERT INTO assignments(id, service_id, person_id, role, locked, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET service_id=excluded.service_id, person_id=excluded.person_id,
role=excluded.role, locked=excluded.locked, note=excluded.note
""", [
.text(assignment.id), .text(assignment.serviceID), .text(assignment.personID),
.text(assignment.role.rawValue), .bool(assignment.locked), .text(assignment.note),
.text(ISO8601DateFormatter().string(from: assignment.createdAt))
])
}
/// Replaces the assignment for one role of a service. Passing nil clears the slot.
public func setAssignment(serviceID: String, role: Role, personID: String?, locked: Bool = false) throws {
try database.transaction {
try database.run("DELETE FROM assignments WHERE service_id=? AND role=?", [.text(serviceID), .text(role.rawValue)])
guard let personID else { return }
let assignment = Assignment(serviceID: serviceID, personID: personID, role: role, locked: locked)
try upsert(assignment)
}
}
public func setAssignment(serviceID: String, personID: String?, role: Role, locked: Bool = false) throws {
try setAssignment(serviceID: serviceID, role: role, personID: personID, locked: locked)
}
public func deleteAssignment(id: String) throws {
try database.run("DELETE FROM assignments WHERE id=?", [.text(id)])
}
public func toggleAssignmentLock(id: String) throws {
try database.run("UPDATE assignments SET locked = CASE locked WHEN 0 THEN 1 ELSE 0 END WHERE id=?", [.text(id)])
}
public func savePlan(_ assignments: [Assignment], in range: DayRange, replaceUnlocked: Bool) throws {
let serviceIDs = try services(in: range).map(\.id)
try database.transaction {
if replaceUnlocked, !serviceIDs.isEmpty {
let placeholders = Array(repeating: "?", count: serviceIDs.count).joined(separator: ",")
try database.run(
"DELETE FROM assignments WHERE locked=0 AND service_id IN (\(placeholders))",
serviceIDs.map(SQLiteValue.text)
)
}
for assignment in assignments {
try upsert(assignment)
}
}
}
private func decodeAssignment(_ row: SQLiteRow) -> Assignment? {
guard let id = row.string("id"), let serviceID = row.string("service_id"),
let personID = row.string("person_id"), let roleRaw = row.string("role"),
let role = Role(rawValue: roleRaw)
else { return nil }
return Assignment(
id: id,
serviceID: serviceID,
personID: personID,
role: role,
locked: row.bool("locked", default: false),
note: row.string("note", default: ""),
createdAt: ISO8601DateFormatter().date(from: row.string("created_at", default: "")) ?? Date()
)
}
// MARK: - Liturgical days
public func liturgicalDays(in range: DayRange) throws -> [LiturgicalDay] {
try database.query("SELECT * FROM liturgical_days WHERE date >= ? AND date <= ? ORDER BY date",
[.dateKey(range.start), .dateKey(range.end)]).compactMap(decodeLiturgicalDay)
}
public func liturgicalDay(on date: Date) throws -> LiturgicalDay? {
try database.query("SELECT * FROM liturgical_days WHERE date=?", [.dateKey(date)]).first.flatMap(decodeLiturgicalDay)
}
public func liturgicalDayCount() throws -> Int {
try database.scalarInt("SELECT COUNT(*) AS value FROM liturgical_days")
}
public func liturgicalYears() throws -> [Int] {
try database.query("SELECT DISTINCT substr(date,1,4) AS year FROM liturgical_days ORDER BY year").compactMap {
Int($0.string("year", default: "0"))
}
}
public func upsert(liturgicalDay: LiturgicalDay) throws {
try database.run("""
INSERT INTO liturgical_days(date, title, rank, color, remark, first_reading, psalm,
second_reading, gospel, is_obligation, source, updated_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(date) DO UPDATE SET title=excluded.title, rank=excluded.rank, color=excluded.color,
remark=excluded.remark, first_reading=excluded.first_reading, psalm=excluded.psalm,
second_reading=excluded.second_reading, gospel=excluded.gospel,
is_obligation=excluded.is_obligation, source=excluded.source, updated_at=excluded.updated_at
""", [
.dateKey(liturgicalDay.date), .text(liturgicalDay.title), .text(liturgicalDay.rank.rawValue),
.text(liturgicalDay.color.rawValue), .text(liturgicalDay.remark),
.text(liturgicalDay.readings.first), .text(liturgicalDay.readings.psalm),
.text(liturgicalDay.readings.second), .text(liturgicalDay.readings.gospel),
.bool(liturgicalDay.isObligation), .text(liturgicalDay.source),
.text(ISO8601DateFormatter().string(from: liturgicalDay.updatedAt))
])
}
public func upsert(liturgicalDays days: [LiturgicalDay]) throws {
try database.transaction {
for day in days { try upsert(liturgicalDay: day) }
}
}
public func replaceLiturgicalYear(_ year: Int, with days: [LiturgicalDay]) throws {
try database.transaction {
try database.run("DELETE FROM liturgical_days WHERE date LIKE ?", [.text("\(year)-%")])
for day in days { try upsert(liturgicalDay: day) }
}
}
private func decodeLiturgicalDay(_ row: SQLiteRow) -> LiturgicalDay? {
guard let date = row.date("date") else { return nil }
return LiturgicalDay(
date: date,
title: row.string("title", default: ""),
rank: LiturgicalRank(rawValue: row.string("rank", default: "")) ?? .weekday,
color: LiturgicalColor(rawValue: row.string("color", default: "g")) ?? .green,
remark: row.string("remark", default: ""),
readings: Readings(
first: row.string("first_reading", default: ""),
psalm: row.string("psalm", default: ""),
second: row.string("second_reading", default: ""),
gospel: row.string("gospel", default: "")
),
isObligation: row.bool("is_obligation"),
source: row.string("source", default: ""),
updatedAt: ISO8601DateFormatter().date(from: row.string("updated_at", default: "")) ?? Date()
)
}
// MARK: - Settings
public func setting(_ key: String) -> String? {
guard let row = try? database.query("SELECT value FROM settings WHERE key=?", [.text(key)]).first else { return nil }
return row.string("value")
}
public func setSetting(_ key: String, value: String) {
try? database.run("INSERT INTO settings(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
[.text(key), .text(value)])
}
public func removeSetting(_ key: String) {
try? database.run("DELETE FROM settings WHERE key=?", [.text(key)])
}
// MARK: - Resources / exchange
public func resources() throws -> ResourceBundle {
ResourceBundle(
churches: try churches(),
people: try people(),
absences: try absences(),
templates: try templates(),
exceptions: try exceptions()
)
}
public func applyResourceBundle(_ bundle: ResourceBundle, replaceExisting: Bool = false) throws {
try database.transaction {
if replaceExisting {
for template in try templates() { try deleteTemplate(id: template.id) }
for person in try people() { try deletePerson(id: person.id) }
for church in try churches() { try deleteChurch(id: church.id) }
}
for church in bundle.churches { try upsert(church) }
for person in bundle.people { try upsert(person) }
for absence in bundle.absences { try upsert(absence) }
for template in bundle.templates { try upsert(template) }
for exception in bundle.exceptions { try upsert(exception) }
}
}
public func exportPlan(range: DayRange, scope: ExchangeScope = .plan) throws -> PlanExchange {
let services = scope == .resources ? [] : try services(in: range)
let serviceIDs = services.map(\.id)
let assignments = scope == .resources ? [] : try assignments(serviceIDs: serviceIDs)
let peopleIDs = Set(assignments.map(\.personID))
let allPeople = try people()
let relevantPeople = scope == .resources ? allPeople : allPeople.filter { peopleIDs.contains($0.id) }
let allAbsences = try absences()
let relevantAbsences = scope == .resources ? allAbsences : allAbsences.filter { peopleIDs.contains($0.personID) }
return PlanExchange(
scope: scope,
range: range,
resources: ResourceBundle(
churches: try churches(),
people: relevantPeople,
absences: relevantAbsences,
templates: try templates(),
exceptions: try exceptions()
),
services: services,
assignments: assignments,
liturgicalDays: scope == .resources ? [] : try liturgicalDays(in: range),
note: "Export aus LektorenPlan · \(DayMath.key(range.start)) bis \(DayMath.key(range.end))"
)
}
public func applyPlanExchange(_ exchange: PlanExchange) throws -> ExchangeSummary {
try database.transaction {
for church in exchange.resources.churches { try upsert(church) }
for person in exchange.resources.people { try upsert(person) }
for absence in exchange.resources.absences { try upsert(absence) }
for template in exchange.resources.templates { try upsert(template) }
for exception in exchange.resources.exceptions { try upsert(exception) }
for day in exchange.liturgicalDays { try upsert(liturgicalDay: day) }
for service in exchange.services { try upsert(service) }
for assignment in exchange.assignments { try upsert(assignment) }
}
return exchange.summary
}
// MARK: - Utilities
private func encode<T: Encodable>(_ value: T) -> String {
guard let data = try? encoder.encode(value) else { return "[]" }
return String(data: data, encoding: .utf8) ?? "[]"
}
private func decode<T: Decodable>(_ string: String) -> T {
guard let data = string.data(using: .utf8),
let value = try? decoder.decode(T.self, from: data)
else {
if T.self == [String].self { return [] as! T }
if T.self == [Int].self { return [] as! T }
return [] as! T
}
return value
}
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 DemoData.seed(into: self)
}
public func databaseSizeBytes() -> Int {
guard path != ":memory:" else { return 0 }
let attributes = try? FileManager.default.attributesOfItem(atPath: path)
return (attributes?[.size] as? NSNumber)?.intValue ?? 0
}
}
+319
View File
@@ -0,0 +1,319 @@
import Foundation
/// All app dates are "calendar days" anchored at noon in the Europe/Berlin time zone.
/// Using noon avoids surprises around daylight-saving transitions while the ISO key
/// remains stable for persistence.
public enum DayMath {
public static var calendar: Calendar {
var cal = Calendar(identifier: .gregorian)
cal.locale = Locale(identifier: "de_DE")
cal.timeZone = TimeZone(identifier: "Europe/Berlin") ?? .current
cal.firstWeekday = 2
cal.minimumDaysInFirstWeek = 4
return cal
}
public static let germanLocale = Locale(identifier: "de_DE")
private static let keyFormatter: DateFormatter = {
let f = DateFormatter()
f.locale = Locale(identifier: "en_US_POSIX")
f.timeZone = TimeZone(identifier: "Europe/Berlin")
f.dateFormat = "yyyy-MM-dd"
return f
}()
private static let weekdayFormatter: DateFormatter = {
let f = DateFormatter()
f.locale = germanLocale
f.timeZone = TimeZone(identifier: "Europe/Berlin")
f.dateFormat = "EEEE"
return f
}()
private static let shortWeekdayFormatter: DateFormatter = {
let f = DateFormatter()
f.locale = germanLocale
f.timeZone = TimeZone(identifier: "Europe/Berlin")
f.dateFormat = "EEE"
return f
}()
private static let monthFormatter: DateFormatter = {
let f = DateFormatter()
f.locale = germanLocale
f.timeZone = TimeZone(identifier: "Europe/Berlin")
f.dateFormat = "MMMM"
return f
}()
private static let shortMonthFormatter: DateFormatter = {
let f = DateFormatter()
f.locale = germanLocale
f.timeZone = TimeZone(identifier: "Europe/Berlin")
f.dateFormat = "MMM"
return f
}()
private static let longFormatter: DateFormatter = {
let f = DateFormatter()
f.locale = germanLocale
f.timeZone = TimeZone(identifier: "Europe/Berlin")
f.dateFormat = "EEEE, d. MMMM yyyy"
return f
}()
private static let mediumFormatter: DateFormatter = {
let f = DateFormatter()
f.locale = germanLocale
f.timeZone = TimeZone(identifier: "Europe/Berlin")
f.dateFormat = "d. MMM yyyy"
return f
}()
public static func normalize(_ date: Date) -> Date {
let comps = calendar.dateComponents([.year, .month, .day], from: date)
return calendar.date(from: DateComponents(
timeZone: calendar.timeZone,
year: comps.year,
month: comps.month,
day: comps.day,
hour: 12
)) ?? date
}
public static func today() -> Date {
normalize(Date())
}
public static func date(fromKey key: String) -> Date? {
guard let date = keyFormatter.date(from: key) else { return nil }
return normalize(date)
}
public static func key(_ date: Date) -> String {
keyFormatter.string(from: date)
}
public static func key(year: Int, month: Int, day: Int) -> String {
String(format: "%04d-%02d-%02d", year, month, day)
}
public static func adding(days: Int, to date: Date) -> Date {
calendar.date(byAdding: .day, value: days, to: normalize(date)) ?? date
}
public static func adding(months: Int, to date: Date) -> Date {
calendar.date(byAdding: .month, value: months, to: normalize(date)) ?? date
}
public static func adding(years: Int, to date: Date) -> Date {
calendar.date(byAdding: .year, value: years, to: normalize(date)) ?? date
}
public static func daysBetween(_ start: Date, _ end: Date) -> Int {
calendar.dateComponents([.day], from: normalize(start), to: normalize(end)).day ?? 0
}
public static func days(in range: DayRange) -> [Date] {
guard range.start <= range.end else { return [] }
var result: [Date] = []
var cursor = normalize(range.start)
let end = normalize(range.end)
while cursor <= end {
result.append(cursor)
cursor = adding(days: 1, to: cursor)
}
return result
}
public static func weekday(_ date: Date) -> Int {
calendar.component(.weekday, from: normalize(date)) // 1 = Sunday … 7 = Saturday
}
public static func isSunday(_ date: Date) -> Bool {
weekday(date) == 1
}
public static func isSaturday(_ date: Date) -> Bool {
weekday(date) == 7
}
public static func weekdayName(_ date: Date) -> String {
weekdayFormatter.string(from: normalize(date))
}
public static func shortWeekdayName(_ date: Date) -> String {
shortWeekdayFormatter.string(from: normalize(date))
}
public static func monthName(_ date: Date) -> String {
monthFormatter.string(from: normalize(date))
}
public static func shortMonthName(_ date: Date) -> String {
shortMonthFormatter.string(from: normalize(date))
}
public static func longString(_ date: Date) -> String {
longFormatter.string(from: normalize(date))
}
public static func mediumString(_ date: Date) -> String {
mediumFormatter.string(from: normalize(date))
}
public static func dayNumber(_ date: Date) -> Int {
calendar.component(.day, from: normalize(date))
}
public static func month(_ date: Date) -> Int {
calendar.component(.month, from: normalize(date))
}
public static func year(_ date: Date) -> Int {
calendar.component(.year, from: normalize(date))
}
public static func startOfYear(_ date: Date) -> Date {
let y = year(date)
return calendar.date(from: DateComponents(timeZone: calendar.timeZone, year: y, month: 1, day: 1, hour: 12)) ?? date
}
public static func endOfYear(_ date: Date) -> Date {
let y = year(date)
return calendar.date(from: DateComponents(timeZone: calendar.timeZone, year: y, month: 12, day: 31, hour: 12)) ?? date
}
public static func startOfMonth(_ date: Date) -> Date {
let comps = calendar.dateComponents([.year, .month], from: date)
return calendar.date(from: DateComponents(
timeZone: calendar.timeZone, year: comps.year, month: comps.month, day: 1, hour: 12
)) ?? date
}
public static func endOfMonth(_ date: Date) -> Date {
let start = startOfMonth(date)
let next = adding(months: 1, to: start)
return adding(days: -1, to: next)
}
public static func startOfQuarter(_ date: Date) -> Date {
let m = month(date)
let quarterStartMonth = ((m - 1) / 3) * 3 + 1
return calendar.date(from: DateComponents(
timeZone: calendar.timeZone, year: year(date), month: quarterStartMonth, day: 1, hour: 12
)) ?? date
}
public static func endOfQuarter(_ date: Date) -> Date {
adding(days: -1, to: adding(months: 3, to: startOfQuarter(date)))
}
public static func quarter(_ date: Date) -> Int {
(month(date) - 1) / 3 + 1
}
public static func monthKey(_ date: Date) -> String {
String(format: "%04d-%02d", year(date), month(date))
}
public static func timeString(minutes: Int) -> String {
let h = max(0, min(23, minutes / 60))
let m = max(0, min(59, minutes % 60))
return String(format: "%02d:%02d", h, m)
}
public static func minutes(hour: Int, minute: Int) -> Int {
hour * 60 + minute
}
public static func ageString(from start: Date, to end: Date) -> String {
let days = abs(daysBetween(start, end)) + 1
return "\(days) Tage"
}
}
public struct DayRange: Hashable, Codable, Sendable, Identifiable {
public var start: Date
public var end: Date
public var id: String { "\(DayMath.key(start))_\(DayMath.key(end))" }
public init(start: Date, end: Date) {
let a = DayMath.normalize(start)
let b = DayMath.normalize(end)
if a <= b {
self.start = a
self.end = b
} else {
self.start = b
self.end = a
}
}
public init(startKey: String, endKey: String) {
let start = DayMath.date(fromKey: startKey) ?? DayMath.today()
let end = DayMath.date(fromKey: endKey) ?? start
self.init(start: start, end: end)
}
public static func quarter(containing date: Date) -> DayRange {
DayRange(start: DayMath.startOfQuarter(date), end: DayMath.endOfQuarter(date))
}
public static func year(_ year: Int) -> DayRange {
let start = DayMath.date(fromKey: DayMath.key(year: year, month: 1, day: 1)) ?? DayMath.today()
let end = DayMath.date(fromKey: DayMath.key(year: year, month: 12, day: 31)) ?? start
return DayRange(start: start, end: end)
}
public static func month(containing date: Date) -> DayRange {
DayRange(start: DayMath.startOfMonth(date), end: DayMath.endOfMonth(date))
}
public static func days(_ count: Int, from date: Date = DayMath.today()) -> DayRange {
DayRange(start: date, end: DayMath.adding(days: max(0, count - 1), to: date))
}
public var days: [Date] { DayMath.days(in: self) }
public var dayCount: Int { max(0, DayMath.daysBetween(start, end) + 1) }
public var monthCount: Int { max(1, (DayMath.year(end) - DayMath.year(start)) * 12 + DayMath.month(end) - DayMath.month(start) + 1) }
public var title: String {
if DayMath.year(start) == DayMath.year(end) {
return "\(DayMath.mediumString(start)) – \(DayMath.mediumString(end))"
}
return "\(DayMath.mediumString(start)) – \(DayMath.mediumString(end))"
}
public var shortTitle: String {
let startLabel = "\(DayMath.dayNumber(start)). \(DayMath.shortMonthName(start))"
let endLabel = "\(DayMath.dayNumber(end)). \(DayMath.shortMonthName(end))"
if DayMath.year(start) == DayMath.year(end) {
return "\(startLabel) – \(endLabel) \(DayMath.year(end))"
}
return "\(startLabel) \(DayMath.year(start)) – \(endLabel) \(DayMath.year(end))"
}
public func contains(_ date: Date) -> Bool {
let d = DayMath.normalize(date)
return d >= start && d <= end
}
public func clamped(to bounds: DayRange) -> DayRange {
DayRange(
start: max(start, bounds.start),
end: min(end, bounds.end)
)
}
public func extend(monthsBefore: Int, monthsAfter: Int) -> DayRange {
DayRange(
start: DayMath.adding(months: -monthsBefore, to: start),
end: DayMath.adding(months: monthsAfter, to: end)
)
}
}
+305
View File
@@ -0,0 +1,305 @@
import Foundation
/// Seeds a realistic working dataset for the parish area of Bad Godesberg.
/// All names, preferences and absences are fictional demo content.
public enum DemoData {
public static func seed(into db: AppDatabase) throws {
let churches = makeChurches()
for church in churches { try db.upsert(church) }
let people = makePeople()
for person in people { try db.upsert(person) }
for absence in makeAbsences() { try db.upsert(absence) }
let templates = makeTemplates()
for template in templates { try db.upsert(template) }
if try db.liturgicalDayCount() == 0 {
try db.upsert(liturgicalDays: LiturgicalSnapshot.loadBundled())
}
try db.generateServices(in: DayRange.year(2025))
try db.generateServices(in: DayRange.year(2026))
try db.generateServices(in: DayRange.year(2027))
try db.generateServices(in: DayRange.year(2028))
try addExceptions(to: db, templates: templates)
try addSpecialServices(to: db)
// Demo history: everything before today is planned, the future is left open
// so the planning workflow and the "offene Dienste" indicators are visible.
let today = DayMath.today()
let yesterday = DayMath.adding(days: -1, to: today)
let pastRange = DayRange(
start: DayMath.date(fromKey: "2025-01-01") ?? today,
end: yesterday
)
let pastServices = try db.services(in: pastRange)
let planner = ServicePlanner(
people: people,
absences: try db.absences(),
services: pastServices,
churches: churches,
options: PlannerOptions(
replaceExisting: true,
respectPreferredWeekdays: true,
weightFairness: 2.4,
maxAssignmentsPerDay: 1
)
)
let result = planner.plan()
try db.savePlan(result.assignments, in: pastRange, replaceUnlocked: true)
// A few locked assignments demonstrate protected planning.
let allAssignments = try db.assignments(in: pastRange)
for (index, assignment) in allAssignments.enumerated() where index % 41 == 0 {
try db.upsert(Assignment(
id: assignment.id,
serviceID: assignment.serviceID,
personID: assignment.personID,
role: assignment.role,
locked: true,
note: assignment.note,
createdAt: assignment.createdAt
))
}
db.setSetting("demoSeededAt", value: ISO8601DateFormatter().string(from: Date()))
db.setSetting("diocese", value: "koeln")
if db.setting("autoSyncLiturgy") == nil {
db.setSetting("autoSyncLiturgy", value: "1")
}
}
private static func makeChurches() -> [Church] {
[
Church(
id: Church.andreasID,
name: "St. Andreas",
shortName: "Andreas",
symbol: .basilica,
colorHex: "#9B5B44",
address: "Andreasstraße 1, 53179 Bonn",
sortIndex: 0,
notes: "Romanischer Kirchturm, Pfarrkirche im Rheinviertel"
),
Church(
id: Church.evergislusID,
name: "St. Evergislus",
shortName: "Evergislus",
symbol: .gothic,
colorHex: "#4E6E5D",
address: "Hardtstraße 13, 53175 Bonn",
sortIndex: 1,
notes: "Neugotische Kirche in Plittersdorf"
),
Church(
id: Church.herzJesuID,
name: "Herz Jesu",
shortName: "Herz Jesu",
symbol: .modern,
colorHex: "#7A5A78",
address: "Beethovenallee, 53173 Bonn",
sortIndex: 2,
notes: "Kirche im Villenviertel"
),
Church(
id: Church.hildegardID,
name: "St. Hildegard",
shortName: "Hildegard",
symbol: .rotunda,
colorHex: "#B0833C",
address: "Im Meisengarten, 53179 Bonn",
sortIndex: 3,
notes: "Rundkirche der 1960er Jahre in Rüngsdorf"
)
]
}
private static func makePeople() -> [Person] {
[
Person(id: "p-anna", firstName: "Anna", lastName: "Berg", roles: [.lector],
email: "anna.berg@example.org", phone: "0228 555 0101",
preferredChurchIDs: [Church.andreasID], preferredWeekdays: [1],
preferredServiceTitles: ["Hochamt"], maxPerMonth: 7,
notes: "Liest besonders gerne die Sonntagslesungen."),
Person(id: "p-markus", firstName: "Markus", lastName: "Weber", roles: [.lector],
email: "markus.weber@example.org", phone: "0228 555 0102",
preferredChurchIDs: [Church.herzJesuID], preferredWeekdays: [1, 7],
preferredServiceTitles: ["Vorabendmesse"], maxPerMonth: 8),
Person(id: "p-elisabeth", firstName: "Elisabeth", lastName: "Klein", roles: [.lector, .helper],
email: "elisabeth.klein@example.org", phone: "0228 555 0103",
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 9,
notes: "Flexibel einsetzbar, auch kurzfristig."),
Person(id: "p-johannes", firstName: "Johannes", lastName: "Schmitz", roles: [.lector],
email: "johannes.schmitz@example.org", preferredChurchIDs: [Church.evergislusID],
preferredWeekdays: [1], preferredServiceTitles: ["Hochamt"], maxPerMonth: 6),
Person(id: "p-maria", firstName: "Maria", lastName: "Hoffmann", roles: [.helper],
preferredChurchIDs: [Church.herzJesuID], preferredWeekdays: [1], maxPerMonth: 8),
Person(id: "p-peter", firstName: "Peter", lastName: "Lang", roles: [.helper],
preferredChurchIDs: [Church.hildegardID], preferredWeekdays: [1], maxPerMonth: 6),
Person(id: "p-susanne", firstName: "Susanne", lastName: "Vogel", roles: [.lector, .helper],
preferredChurchIDs: [Church.andreasID], preferredWeekdays: [1], maxPerMonth: 8),
Person(id: "p-thomas", firstName: "Thomas", lastName: "Neumann", roles: [.lector],
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 10,
notes: "Springerfunktion."),
Person(id: "p-claudia", firstName: "Claudia", lastName: "Roth", roles: [.helper],
preferredChurchIDs: [Church.evergislusID], preferredWeekdays: [1, 4], maxPerMonth: 7),
Person(id: "p-michael", firstName: "Michael", lastName: "Braun", roles: [.helper],
preferredChurchIDs: [Church.andreasID], preferredWeekdays: [1], maxPerMonth: 8),
Person(id: "p-julia", firstName: "Julia", lastName: "Schröder", roles: [.lector, .helper],
preferredChurchIDs: [Church.herzJesuID, Church.hildegardID], preferredWeekdays: [1, 7],
maxPerMonth: 8),
Person(id: "p-andreas", firstName: "Andreas", lastName: "Wolff", roles: [.lector],
preferredChurchIDs: [Church.hildegardID], preferredWeekdays: [1],
preferredServiceTitles: ["Wort-Gottes-Feier"], maxPerMonth: 6),
Person(id: "p-birgit", firstName: "Birgit", lastName: "Sauer", roles: [.helper],
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 9),
Person(id: "p-daniel", firstName: "Daniel", lastName: "Krüger", roles: [.lector],
preferredChurchIDs: [Church.herzJesuID, Church.andreasID], preferredWeekdays: [1, 2, 5],
maxPerMonth: 7),
Person(id: "p-petra", firstName: "Petra", lastName: "Sommer", roles: [.helper],
preferredChurchIDs: [Church.evergislusID, Church.hildegardID], preferredWeekdays: [1, 7],
maxPerMonth: 7),
Person(id: "p-stefan", firstName: "Stefan", lastName: "Haas", roles: [.lector, .helper],
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 9),
Person(id: "p-monika", firstName: "Monika", lastName: "Albrecht", roles: [.helper],
preferredChurchIDs: [Church.andreasID], preferredWeekdays: [1, 3], maxPerMonth: 6),
Person(id: "p-christoph", firstName: "Christoph", lastName: "Mertens", roles: [.lector],
preferredChurchIDs: [Church.evergislusID], preferredWeekdays: [1, 7],
preferredServiceTitles: ["Vorabendmesse"], maxPerMonth: 7),
Person(id: "p-simone", firstName: "Simone", lastName: "Becker", roles: [.helper],
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 8),
Person(id: "p-martin", firstName: "Martin", lastName: "Fuchs", roles: [.lector],
preferredChurchIDs: [], preferredWeekdays: [1, 3], maxPerMonth: 7),
Person(id: "p-ursula", firstName: "Ursula", lastName: "Peters", roles: [.helper],
preferredChurchIDs: [], preferredWeekdays: [3, 4, 5], maxPerMonth: 8,
notes: "Werktagsmessen."),
Person(id: "p-frank", firstName: "Frank", lastName: "Lorenz", roles: [.lector],
preferredChurchIDs: [], preferredWeekdays: [2, 3, 5], maxPerMonth: 8,
notes: "Werktagsmessen.")
]
}
private static func makeAbsences() -> [Absence] {
func date(_ key: String) -> Date { DayMath.date(fromKey: key) ?? DayMath.today() }
return [
Absence(personID: "p-anna", start: date("2026-12-20"), end: date("2027-01-06"), reason: "Weihnachtsreise"),
Absence(personID: "p-markus", start: date("2026-11-10"), end: date("2026-11-24"), reason: "Kur"),
Absence(personID: "p-maria", start: date("2027-03-01"), end: date("2027-03-15"), reason: "Fortbildung"),
Absence(personID: "p-peter", start: date("2026-12-24"), end: date("2026-12-26"), reason: "Familie"),
Absence(personID: "p-susanne", start: date("2026-08-01"), end: date("2026-08-21"), reason: "Urlaub"),
Absence(personID: "p-michael", start: date("2026-11-01"), end: date("2026-11-08"), reason: "Urlaub"),
Absence(personID: "p-julia", start: date("2027-05-01"), end: date("2027-05-14"), reason: "Urlaub"),
Absence(personID: "p-birgit", start: date("2026-11-15"), end: date("2026-11-22"), reason: "Dienstreise"),
Absence(personID: "p-daniel", start: date("2026-12-01"), end: date("2026-12-12"), reason: "Umzug"),
Absence(personID: "p-petra", start: date("2027-02-01"), end: date("2027-02-14"), reason: "Winterurlaub"),
Absence(personID: "p-thomas", start: date("2027-04-01"), end: date("2027-04-20"), reason: "Reha"),
Absence(personID: "p-simone", start: date("2026-12-24"), end: date("2027-01-02"), reason: "Familienbesuch"),
Absence(personID: "p-ursula", start: date("2026-09-07"), end: date("2026-09-20"), reason: "Urlaub"),
Absence(personID: "p-frank", start: date("2026-11-23"), end: date("2026-12-04"), reason: "Kur")
]
}
private static func makeTemplates() -> [ServiceTemplate] {
let from = DayMath.date(fromKey: "2024-01-01") ?? DayMath.today()
func t(_ id: String, _ church: String, _ weekday: Int, _ hour: Int, _ minute: Int,
_ title: String, _ lectors: Int = 1, _ helpers: Int = 1, notes: String = "") -> ServiceTemplate {
ServiceTemplate(
id: id,
churchID: church,
weekday: weekday,
timeMinutes: DayMath.minutes(hour: hour, minute: minute),
title: title,
lectorsNeeded: lectors,
helpersNeeded: helpers,
validFrom: from,
notes: notes
)
}
return [
t("t-andreas-so-hl", Church.andreasID, 1, 9, 30, "Hochamt", 1, 2, notes: "Sonntägliches Hochamt"),
t("t-andreas-so-ab", Church.andreasID, 1, 18, 0, "Abendmesse", 1, 1),
t("t-andreas-mi", Church.andreasID, 4, 8, 30, "Werktagsmesse", 1, 1),
t("t-evergislus-sa", Church.evergislusID, 7, 18, 0, "Vorabendmesse", 1, 1, notes: "Samstagabend"),
t("t-evergislus-so", Church.evergislusID, 1, 11, 0, "Hochamt", 1, 2),
t("t-evergislus-do", Church.evergislusID, 5, 8, 30, "Werktagsmesse", 1, 1),
t("t-herzjesu-sa", Church.herzJesuID, 7, 17, 0, "Vorabendmesse", 1, 1),
t("t-herzjesu-so", Church.herzJesuID, 1, 10, 0, "Hochamt", 1, 2),
t("t-herzjesu-di", Church.herzJesuID, 3, 18, 0, "Werktagsmesse", 1, 1),
t("t-herzjesu-fr", Church.herzJesuID, 6, 8, 30, "Werktagsmesse", 1, 1),
t("t-hildegard-so", Church.hildegardID, 1, 9, 0, "Messe", 1, 1),
t("t-hildegard-wgf", Church.hildegardID, 1, 11, 30, "Wort-Gottes-Feier", 1, 0, notes: "Lektorat, keine Kommunionspendung"),
t("t-hildegard-mi", Church.hildegardID, 4, 18, 30, "Werktagsmesse", 1, 1)
]
}
private static func addExceptions(to db: AppDatabase, templates: [ServiceTemplate]) throws {
let goodFridays = ["2025-04-18", "2026-04-03", "2027-03-26"]
let christmasEves = ["2025-12-24", "2027-12-24"]
for template in templates {
if template.weekday == 6, template.churchID == Church.herzJesuID {
for key in goodFridays {
if let date = DayMath.date(fromKey: key) {
try db.upsert(ServiceException(templateID: template.id, date: date, reason: "Karfreitag – keine Werktagsmesse"))
}
}
}
if template.weekday == 4 {
for key in christmasEves {
if let date = DayMath.date(fromKey: key) {
try db.upsert(ServiceException(templateID: template.id, date: date, reason: "Heiliger Abend"))
}
}
}
}
// Holy Saturday: the Easter Vigil replaces the regular Saturday evening mass.
if let evergislus = templates.first(where: { $0.id == "t-evergislus-sa" }) {
for key in ["2025-04-19", "2026-04-04", "2027-03-27"] {
if let date = DayMath.date(fromKey: key) {
try db.upsert(ServiceException(templateID: evergislus.id, date: date, reason: "Osternacht"))
}
}
}
}
private static func addSpecialServices(to db: AppDatabase) throws {
func date(_ key: String) -> Date { DayMath.date(fromKey: key) ?? DayMath.today() }
let specials: [ServiceOccurrence] = [
ServiceOccurrence(churchID: Church.andreasID, date: date("2025-12-24"), timeMinutes: DayMath.minutes(hour: 16, minute: 0),
title: "Familienchristmette", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
notes: "Kinder- und Familienchristmette mit Krippenspiel"),
ServiceOccurrence(churchID: Church.herzJesuID, date: date("2025-12-24"), timeMinutes: DayMath.minutes(hour: 22, minute: 0),
title: "Christmette", lectorsNeeded: 1, helpersNeeded: 2, kind: .special),
ServiceOccurrence(churchID: Church.evergislusID, date: date("2025-04-19"), timeMinutes: DayMath.minutes(hour: 21, minute: 0),
title: "Osternacht", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
notes: "Hochfest der Auferstehung, Lichterfeier"),
ServiceOccurrence(churchID: Church.andreasID, date: date("2026-04-04"), timeMinutes: DayMath.minutes(hour: 21, minute: 0),
title: "Osternacht", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
notes: "Lichterfeier mit Taufgedächtnis"),
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.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"),
ServiceOccurrence(churchID: Church.herzJesuID, date: date("2026-12-24"), timeMinutes: DayMath.minutes(hour: 22, minute: 0),
title: "Christmette", lectorsNeeded: 1, helpersNeeded: 2, kind: .special),
ServiceOccurrence(churchID: Church.evergislusID, date: date("2027-03-27"), timeMinutes: DayMath.minutes(hour: 21, minute: 0),
title: "Osternacht", lectorsNeeded: 1, helpersNeeded: 1, kind: .special),
ServiceOccurrence(churchID: Church.herzJesuID, date: date("2027-06-04"), timeMinutes: DayMath.minutes(hour: 10, minute: 0),
title: "Fronleichnamsprozession", lectorsNeeded: 1, helpersNeeded: 2, kind: .special,
notes: "Gemeinsame Prozession der Pfarrgemeinschaft"),
ServiceOccurrence(churchID: Church.andreasID, date: date("2027-12-24"), timeMinutes: DayMath.minutes(hour: 16, minute: 0),
title: "Familienchristmette", lectorsNeeded: 1, helpersNeeded: 1, kind: .special),
ServiceOccurrence(churchID: Church.herzJesuID, date: date("2027-12-24"), timeMinutes: DayMath.minutes(hour: 22, minute: 0),
title: "Christmette", lectorsNeeded: 1, helpersNeeded: 2, kind: .special)
]
for service in specials { try db.upsert(service) }
}
}
@@ -0,0 +1,247 @@
import Foundation
// MARK: - Bundled offline snapshot
private struct SnapshotFile: Decodable {
struct Day: Decodable {
let date: String
let title: String
let rank: String
let color: String
let bem: String
let l1: String
let ap: String
let l2: String
let ev: String
let obligation: Bool
}
let version: Int
let source: String
let diocese: String
let years: [Int]
let days: [Day]
}
public enum LiturgicalSnapshot {
public static let sourceLabel = "Daten von www.eucharistiefeier.de"
public static func loadBundled() -> [LiturgicalDay] {
guard let url = bundledURL(),
let data = try? Data(contentsOf: url),
let file = try? JSONDecoder().decode(SnapshotFile.self, from: data)
else {
return []
}
return file.days.compactMap { day in
guard let date = DayMath.date(fromKey: day.date) else { return nil }
let rank = LiturgicalRank(rawValue: day.rank) ?? .weekday
return LiturgicalDay(
date: date,
title: day.title,
rank: rank,
color: LiturgicalColor(apiValue: day.color),
remark: day.bem,
readings: Readings(first: day.l1, psalm: day.ap, second: day.l2, gospel: day.ev),
isObligation: day.obligation,
source: sourceLabel
)
}
}
public static func bundledYears() -> [Int] {
guard let url = bundledURL(),
let data = try? Data(contentsOf: url),
let file = try? JSONDecoder().decode(SnapshotFile.self, from: data)
else { return [] }
return file.years
}
private static func bundledURL() -> URL? {
let candidates: [URL?] = [
Bundle.module.url(forResource: "liturgical-snapshot", withExtension: "json"),
Bundle.main.url(forResource: "liturgical-snapshot", withExtension: "json"),
Bundle.main.resourceURL?.appendingPathComponent("liturgical-snapshot.json")
]
return candidates.compactMap { $0 }.first { FileManager.default.fileExists(atPath: $0.path) }
}
}
// MARK: - Live API
public enum LiturgicalAPIError: LocalizedError {
case invalidURL
case badStatus(Int)
case invalidPayload(String)
case emptyYear(Int)
public var errorDescription: String? {
switch self {
case .invalidURL:
return "Die Kalender-URL konnte nicht erstellt werden."
case .badStatus(let code):
return "Der liturgische Kalender antwortete mit HTTP \(code)."
case .invalidPayload(let detail):
return "Die Kalenderdaten konnten nicht gelesen werden (\(detail))."
case .emptyYear(let year):
return "Für \(year) wurden keine liturgischen Daten geliefert."
}
}
}
public struct LiturgicalCalendarAPI: Sendable {
public var diocese: String
public var endpoint: URL
public init(diocese: String = "koeln", endpoint: URL = URL(string: "https://www.eucharistiefeier.de/lk/api.php")!) {
self.diocese = diocese
self.endpoint = endpoint
}
public func fetch(year: Int) async throws -> [LiturgicalDay] {
guard var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false) else {
throw LiturgicalAPIError.invalidURL
}
components.queryItems = [
URLQueryItem(name: "kal", value: diocese),
URLQueryItem(name: "jahr", value: String(year)),
URLQueryItem(name: "format", value: "json"),
URLQueryItem(name: "info", value: "wdtrflu"),
URLQueryItem(name: "dup", value: "e"),
URLQueryItem(name: "bahn", value: "j")
]
guard let url = components.url else { throw LiturgicalAPIError.invalidURL }
var request = URLRequest(url: url)
request.timeoutInterval = 45
request.setValue("LektorenPlan/0.1 (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)
if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
throw LiturgicalAPIError.badStatus(http.statusCode)
}
return try Self.parse(data: data, year: year)
}
public static func parse(data: Data, year: Int) throws -> [LiturgicalDay] {
guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let celebrations = object["Zelebrationen"]
else {
throw LiturgicalAPIError.invalidPayload("Zelebrationen fehlen")
}
var entries: [[String: Any]] = []
if let dict = celebrations as? [String: Any] {
entries = dict.values.compactMap { $0 as? [String: Any] }
} else if let array = celebrations as? [[String: Any]] {
entries = array
}
let grouped = Dictionary(grouping: entries) { ($0["Datum"] as? String) ?? "" }
var days: [LiturgicalDay] = []
for dateKey in grouped.keys.sorted() {
guard dateKey.hasPrefix(String(year)), let date = DayMath.date(fromKey: dateKey) else { continue }
let raw = grouped[dateKey] ?? []
let valid = raw.filter { entry in
let title = (entry["Tl"] as? String) ?? ""
let remark = (entry["Bem"] as? String) ?? ""
if title.contains("Bahnlesungen") { return false }
if title.hasPrefix("Kommemoration") { return false }
if title == "Weihe der eigenen Kirche" && remark.hasPrefix("Wenn") { return false }
return true
}
guard !valid.isEmpty else { continue }
let best = valid.max { score($0, date: date) < score($1, date: date) } ?? valid[0]
var readingEntry = best
let bestTitle = (best["Tl"] as? String) ?? ""
if ((best["L1"] as? String) ?? "").isEmpty && ((best["EV"] as? String) ?? "").isEmpty {
readingEntry = valid.max {
readingLength($0) < readingLength($1)
} ?? best
}
let title = bestTitle
let rank = LiturgicalRank(rawValue: (best["Rang"] as? String) ?? "") ?? .weekday
let colorValue = (best["Farbe"] as? String).flatMap { $0.isEmpty ? nil : $0 }
?? (readingEntry["Farbe"] as? String)
?? ""
let readings = Readings(
first: (readingEntry["L1"] as? String) ?? "",
psalm: (readingEntry["AP"] as? String) ?? "",
second: (readingEntry["L2"] as? String) ?? "",
gospel: (readingEntry["EV"] as? String) ?? ""
)
days.append(LiturgicalDay(
date: date,
title: title,
rank: rank,
color: LiturgicalColor(apiValue: colorValue),
remark: (best["Bem"] as? String) ?? "",
readings: readings,
isObligation: LiturgicalCalendarEngine.isObligation(date: date, title: title),
source: LiturgicalSnapshot.sourceLabel
))
}
guard !days.isEmpty else { throw LiturgicalAPIError.emptyYear(year) }
// Complete gaps with the local calendar so a plan never has empty rows.
let existing = Set(days.map(\.dateKey))
let start = DayMath.date(fromKey: DayMath.key(year: year, month: 1, day: 1))!
let end = DayMath.date(fromKey: DayMath.key(year: year, month: 12, day: 31))!
for day in DayMath.days(in: DayRange(start: start, end: end)) where !existing.contains(DayMath.key(day)) {
days.append(LiturgicalCalendarEngine.localDay(for: day))
}
return days.sorted { $0.date < $1.date }
}
private static func readingLength(_ entry: [String: Any]) -> Int {
["L1", "AP", "L2", "EV"].reduce(0) { total, key in
total + ((entry[key] as? String)?.count ?? 0)
}
}
private static func score(_ entry: [String: Any], date: Date) -> Int {
var value = 0
let rank = (entry["Rang"] as? String) ?? ""
switch rank {
case "H": value += 120
case "F": value += 110
case "G": value += 80
case "g": value += 60
default: value += 50
}
let title = (entry["Tl"] as? String) ?? ""
let remark = (entry["Bem"] as? String) ?? ""
let lowerTitle = title.lowercased()
if DayMath.isSunday(date) {
if lowerTitle.contains("sonntag") || lowerTitle.contains("taufe des herrn") {
value += 100
}
if rank.isEmpty { value += 30 }
}
if remark.contains("Am Tag") { value += 18 }
else if remark.contains("Am Morgen") { value += 12 }
else if remark.contains("Am Vorabend") { value -= 4 }
else if remark.contains("In der Heiligen Nacht") { value += 5 }
if remark.contains("Hochfest") { value += 10 }
if title.range(of: #"^\d{1,2}\.\s"#, options: .regularExpression) != nil { value -= 25 }
if !(((entry["L1"] as? String) ?? "").isEmpty && ((entry["EV"] as? String) ?? "").isEmpty) { value += 20 }
if lowerTitle.contains("im jahreskreis") || lowerTitle.contains("osterzeit") { value += 5 }
return value
}
}
// MARK: - Combined loader
public enum LiturgicalData {
/// Inserts the bundled snapshot when the database does not yet know these years.
public static func bundledDays(notOlderThan existing: Set<String>) -> [LiturgicalDay] {
LiturgicalSnapshot.loadBundled().filter { !existing.contains($0.dateKey) }
}
}
@@ -0,0 +1,348 @@
import Foundation
public enum LiturgicalCalendarEngine {
// MARK: - Moveable feasts
public static func easterSunday(year: Int) -> Date {
let a = year % 19
let b = year / 100
let c = year % 100
let d = b / 4
let e = b % 4
let f = (b + 8) / 25
let g = (b - f + 1) / 3
let h = (19 * a + b - d - g + 15) % 30
let i = c / 4
let k = c % 4
let l = (32 + 2 * e + 2 * i - h - k) % 7
let m = (a + 11 * h + 22 * l) / 451
let month = (h + l - 7 * m + 114) / 31
let day = ((h + l - 7 * m + 114) % 31) + 1
return DayMath.date(fromKey: DayMath.key(year: year, month: month, day: day)) ?? DayMath.today()
}
public static func easterOffset(_ offset: Int, year: Int) -> Date {
DayMath.adding(days: offset, to: easterSunday(year: year))
}
public static func ashWednesday(year: Int) -> Date { easterOffset(-46, year: year) }
public static func palmSunday(year: Int) -> Date { easterOffset(-7, year: year) }
public static func holyThursday(year: Int) -> Date { easterOffset(-3, year: year) }
public static func goodFriday(year: Int) -> Date { easterOffset(-2, year: year) }
public static func holySaturday(year: Int) -> Date { easterOffset(-1, year: year) }
public static func ascension(year: Int) -> Date { easterOffset(39, year: year) }
public static func pentecost(year: Int) -> Date { easterOffset(49, year: year) }
public static func corpusChristi(year: Int) -> Date { easterOffset(60, year: year) }
public static func sacredHeart(year: Int) -> Date { easterOffset(68, year: year) }
public static func trinitySunday(year: Int) -> Date { easterOffset(56, year: year) }
/// First Sunday of Advent (the Sunday between 27 November and 3 December).
public static func adventStart(year: Int) -> Date {
let christmasEve = DayMath.date(fromKey: DayMath.key(year: year, month: 12, day: 24)) ?? DayMath.today()
var sunday = christmasEve
while DayMath.weekday(sunday) != 1 {
sunday = DayMath.adding(days: -1, to: sunday)
}
return DayMath.adding(days: -21, to: sunday)
}
public static func christKing(year: Int) -> Date {
DayMath.adding(days: -7, to: adventStart(year: year))
}
public static func baptismOfTheLord(year: Int) -> Date {
let epiphany = DayMath.date(fromKey: DayMath.key(year: year, month: 1, day: 6)) ?? DayMath.today()
var sunday = DayMath.adding(days: 1, to: epiphany)
while DayMath.weekday(sunday) != 1 {
sunday = DayMath.adding(days: 1, to: sunday)
}
// If Epiphany itself falls on 7 or 8 January, the baptism is moved to the Monday.
if DayMath.month(epiphany) == 1, DayMath.dayNumber(epiphany) >= 7 {
return DayMath.adding(days: 1, to: epiphany)
}
return sunday
}
// MARK: - Seasons
public static func season(for date: Date) -> LiturgicalSeason {
let day = DayMath.normalize(date)
let y = DayMath.year(day)
let advent = adventStart(year: y)
let christmas = DayMath.date(fromKey: DayMath.key(year: y, month: 12, day: 25)) ?? day
let baptism = baptismOfTheLord(year: y)
let ash = ashWednesday(year: y)
let holyThursday = self.holyThursday(year: y)
let easter = easterSunday(year: y)
let pentecost = self.pentecost(year: y)
if day >= advent && day < christmas { return .advent }
if day >= christmas || day <= baptism { return .christmas }
if day >= ash && day < holyThursday { return .lent }
if day >= easter && day <= pentecost { return .easter }
if day > pentecost && day < advent { return .ordinary }
return .ordinary
}
public static func seasonName(for date: Date) -> String {
season(for: date).title
}
// MARK: - Obligation
public static func isObligation(date: Date, title: String = "") -> Bool {
if DayMath.isSunday(date) { return true }
let month = DayMath.month(date)
let day = DayMath.dayNumber(date)
switch (month, day) {
case (1, 1), (1, 6), (8, 15), (11, 1), (12, 25):
return true
default:
break
}
let lower = title.lowercased()
if lower.contains("fronleichnam") { return true }
if lower.contains("christi himmelfahrt") { return true }
if lower.contains("pfingsten") && !lower.contains("vorabend") { return true }
if lower.contains("ostersonntag") || lower.contains("osternacht") { return true }
return false
}
// MARK: - Symbols
public static func symbol(for title: String, rank: LiturgicalRank, date: Date) -> FeastSymbol {
let t = title.lowercased()
if t.contains("weihnacht") || t.contains("geburt des herrn") { return .star }
if t.contains("erscheinung") { return .star }
if t.contains("ostern") || t.contains("auferstehung") { return .sun }
if t.contains("pfingst") || t.contains("heiliger geist") { return .flame }
if t.contains("fronleichnam") || t.contains("abendmahl") || t.contains("gründonnerstag") { return .candle }
if t.contains("herz jesu") { return .heart }
if t.contains("christkönig") { return .crown }
if t.contains("allerheiligen") { return .crown }
if t.contains("maria") || t.contains("mariä") { return .lily }
if t.contains("kreuz") || t.contains("kreuzerhöhung") { return .cross }
if t.contains("taufe") { return .dove }
if t.contains("wort gottes") || t.contains("evangel") { return .book }
if t.contains("lichtmess") || t.contains("darstellung") { return .candle }
if t.contains("fronleichnam") { return .candle }
if rank == .solemnity { return .cross }
if rank == .feast { return .cross }
return .book
}
// MARK: - Local fallback
private static let fixedReadings: [String: Readings] = [
"01-01": Readings(first: "Num 6, 22-27", psalm: "Ps 67 (66), 2-3.5.6 u. 8 (R: 2a)", second: "Gal 4, 4-7", gospel: "Lk 2, 16-21"),
"01-06": Readings(first: "Jes 60, 1-6", psalm: "Ps 72 (71), 1-2.7-8.10-11.12-13 (R: 11)", second: "Eph 3, 2-3a.5-6", gospel: "Mt 2, 1-12"),
"02-02": Readings(first: "Mal 3, 1-4", psalm: "Ps 24 (23), 7-8.9-10 (R: 8a)", second: "Hebr 2, 14-18", gospel: "Lk 2, 22-40"),
"03-19": Readings(first: "2 Sam 7, 4-5a.12-14a.16", psalm: "Ps 89 (88), 2-3.4-5.27.29 (R: 37)", second: "Röm 4, 13.16-18.22", gospel: "Mt 1, 16.18-21.24a"),
"03-25": Readings(first: "Jes 7, 10-14", psalm: "Ps 40 (39), 5-6.7-8a.8b-10 (R: 8a.9a)", second: "Hebr 10, 4-10", gospel: "Lk 1, 26-38"),
"06-24": Readings(first: "Jes 49, 1-6", psalm: "Ps 139 (138), 1-3.13-14ab.14c-15 (R: 14a)", second: "Apg 13, 22-26", gospel: "Lk 1, 57-66.80"),
"06-29": Readings(first: "Apg 12, 1-11", psalm: "Ps 34 (33), 2-3.4-5.6-7.8-9 (R: 5b)", second: "2 Tim 4, 6-8.17-18", gospel: "Mt 16, 13-19"),
"08-15": Readings(first: "Offb 11, 19a; 12, 1-6a.10ab", psalm: "Ps 45 (44), 11-12.16-17 (R: 10b)", second: "1 Kor 15, 20-27", gospel: "Lk 1, 39-56"),
"09-14": Readings(first: "Num 21, 4b-9", psalm: "Ps 78 (77), 1-2.34-35.36-37.38 (R: 7b)", second: "Phil 2, 6-11", gospel: "Joh 3, 13-17"),
"11-01": Readings(first: "Offb 7, 2-4.9-14", psalm: "Ps 24 (23), 1-2.3-4.5-6 (R: vgl. 6)", second: "1 Joh 3, 1-3", gospel: "Mt 5, 1-12a"),
"11-02": Readings(first: "Jes 25, 6a.7-9", psalm: "Ps 23 (22), 1-3a.3b-4.5.6 (R: 1)", second: "Röm 8, 14-23", gospel: "Mt 25, 31-46"),
"12-08": Readings(first: "Gen 3, 9-15.20", psalm: "Ps 98 (97), 1.2-3ab.3cd-4 (R: 1a)", second: "Eph 1, 3-6.11-12", gospel: "Lk 1, 26-38"),
"12-24": Readings(first: "2 Sam 7, 1-5.8b-12.14a.16", psalm: "Ps 89 (88), 2-3.20a u. 4-5.27 u. 29 (R: 2a)", second: "", gospel: "Lk 1, 67-79"),
"12-25": Readings(first: "Jes 52, 7-10", psalm: "Ps 98 (97), 1.2-3b.3c-4.5-6 (R: vgl. 3cd)", second: "Hebr 1, 1-6", gospel: "Joh 1, 1-18"),
"12-26": Readings(first: "Apg 6, 8-10; 7, 54-59", psalm: "Ps 31 (30), 3-4.6.8.17 (R: 6a)", second: "", gospel: "Mt 10, 17-22")
]
private static let easterReadings: [Int: Readings] = [
-46: Readings(first: "Joel 2, 12-18", psalm: "Ps 51 (50), 3-4.5-6a.12-13.14 u. 17 (R: vgl. 3a)", second: "2 Kor 5, 20 - 6, 2", gospel: "Mt 6, 1-6.16-18"),
-7: Readings(first: "Jes 50, 4-7", psalm: "Ps 22 (21), 8-9.17-18a.19-20.23-24 (R: 2a)", second: "Phil 2, 6-11", gospel: "Mt 21, 1-11"),
-3: Readings(first: "Ex 12, 1-8.11-14", psalm: "Ps 116 (115), 12-13.15-16bc.17-18 (R: vgl. 1 Kor 10, 16)", second: "1 Kor 11, 23-26", gospel: "Joh 13, 1-15"),
-2: Readings(first: "Jes 52, 13 - 53, 12", psalm: "Ps 31 (30), 2 u. 6.12-13.15-16.17 u. 25 (R: Lk 23, 46)", second: "Hebr 4, 14-16; 5, 7-9", gospel: "Joh 18, 1 - 19, 42"),
0: Readings(first: "Apg 10, 34a.37-43", psalm: "Ps 118 (117), 1-2.16-17.22-23 (R: vgl. 24)", second: "Kol 3, 1-4 oder 1 Kor 5, 6b-8", gospel: "Joh 20, 1-9"),
39: Readings(first: "Apg 1, 1-11", psalm: "Ps 47 (46), 2-3.6-7.8-9 (R: 6)", second: "Eph 1, 17-23", gospel: "Mk 16, 15-20"),
49: Readings(first: "Apg 2, 1-11", psalm: "Ps 104 (103), 1-2.24-25.29-30.31 u. 34 (R: vgl. 30)", second: "1 Kor 12, 3b-7.12-13", gospel: "Joh 20, 19-23"),
56: Readings(first: "Spr 8, 22-31", psalm: "Ps 8, 4-5.6-7.8-9 (R: 2a)", second: "Röm 5, 1-5", gospel: "Joh 16, 12-15"),
60: Readings(first: "Dtn 8, 2-3.14-16a", psalm: "Ps 147, 12-13.14-15.19-20 (R: 12a)", second: "1 Kor 10, 16-17", gospel: "Joh 6, 51-58"),
68: Readings(first: "Hos 11, 1.3-4.8c-9", psalm: "Jes 12, 2-3.4bcd.5-6 (R: 3)", second: "Eph 3, 8-12.14-19", gospel: "Joh 19, 31-37")
]
public static func localDay(for date: Date) -> LiturgicalDay {
let day = DayMath.normalize(date)
let y = DayMath.year(day)
let m = DayMath.month(day)
let d = DayMath.dayNumber(day)
let key = String(format: "%02d-%02d", m, d)
let weekday = DayMath.weekday(day)
let easter = easterSunday(year: y)
let offset = DayMath.daysBetween(easter, day)
var title = ""
var rank: LiturgicalRank = .weekday
var color: LiturgicalColor = .green
var readings = Readings()
var remark = ""
// Moveable celebrations take precedence over fixed ones.
switch offset {
case -46:
title = "Aschermittwoch"; rank = .weekday; color = .violet
readings = easterReadings[-46] ?? Readings()
case -7:
title = "Palmsonntag"; rank = .feast; color = .red
readings = easterReadings[-7] ?? Readings()
case -3:
title = "Gründonnerstag"; rank = .solemnity; color = .white
readings = easterReadings[-3] ?? Readings()
case -2:
title = "Karfreitag"; rank = .solemnity; color = .red
readings = easterReadings[-2] ?? Readings()
case -1:
title = "Karsamstag"; rank = .weekday; color = .violet
case 0:
title = "Ostersonntag"; rank = .solemnity; color = .white
readings = easterReadings[0] ?? Readings()
remark = "Hochfest der Auferstehung des Herrn"
case 1:
title = "Ostermontag"; rank = .solemnity; color = .white
readings = Readings(first: "Apg 2, 14.22-33", psalm: "Ps 16 (15), 1-2a u. 5.7-8.9-10.11 (R: 11a)", second: "", gospel: "Mt 28, 8-15")
case 39:
title = "Christi Himmelfahrt"; rank = .solemnity; color = .white
readings = easterReadings[39] ?? Readings()
case 49:
title = "Pfingsten"; rank = .solemnity; color = .red
readings = easterReadings[49] ?? Readings()
remark = "Hochfest des Heiligen Geistes"
case 50:
title = "Pfingstmontag"; rank = .solemnity; color = .red
readings = Readings(first: "Apg 10, 34a.37-43", psalm: "Ps 118 (117), 1-2.16-17.22-23 (R: vgl. 24)", second: "Kol 3, 1-4", gospel: "Joh 20, 1-9")
case 56:
title = "Dreifaltigkeitssonntag"; rank = .solemnity; color = .white
readings = easterReadings[56] ?? Readings()
case 60:
title = "Fronleichnam"; rank = .solemnity; color = .white
readings = easterReadings[60] ?? Readings()
remark = "Hochfest des Leibes und Blutes Christi"
case 68:
title = "Heiligstes Herz Jesu"; rank = .solemnity; color = .white
readings = easterReadings[68] ?? Readings()
default:
break
}
if title.isEmpty {
switch key {
case "01-01": title = "Neujahr – Hochfest der Gottesmutter Maria"; rank = .solemnity; color = .white
case "01-06": title = "Erscheinung des Herrn"; rank = .solemnity; color = .white
case "02-02": title = "Darstellung des Herrn"; rank = .feast; color = .white
case "03-19": title = "Hl. Josef, Bräutigam der Gottesmutter"; rank = .solemnity; color = .white
case "03-25": title = "Verkündigung des Herrn"; rank = .solemnity; color = .white
case "06-24": title = "Geburt Johannes' des Täufers"; rank = .solemnity; color = .white
case "06-29": title = "Petrus und Paulus"; rank = .solemnity; color = .red
case "08-15": title = "Mariä Aufnahme in den Himmel"; rank = .solemnity; color = .white
case "09-14": title = "Kreuzerhöhung"; rank = .feast; color = .red
case "11-01": title = "Allerheiligen"; rank = .solemnity; color = .white
case "11-02": title = "Allerseelen"; rank = .weekday; color = .violet
case "12-08": title = "Mariä Empfängnis"; rank = .solemnity; color = .white
case "12-24": title = "Heiliger Abend"; rank = .weekday; color = .white
case "12-25": title = "Weihnachten – Hochfest der Geburt des Herrn"; rank = .solemnity; color = .white
case "12-26": title = "Hl. Stephanus"; rank = .feast; color = .red
default: break
}
if let r = fixedReadings[key] { readings = r }
}
if title.isEmpty {
if weekday == 1 {
title = sundayTitle(for: day)
color = DayMath.weekday(day) == 1 ? .green : .green
if let fest = seasonalSundayRank(for: day) {
rank = fest
}
} else {
title = weekdayTitle(for: day)
if season(for: day) == .advent || season(for: day) == .lent {
color = .violet
} else if season(for: day) == .christmas || season(for: day) == .easter {
color = .white
} else {
color = .green
}
}
}
if rank == .solemnity { color = .white }
if rank == .feast && color == .green { color = .red }
return LiturgicalDay(
date: day,
title: title,
rank: rank,
color: color,
remark: remark,
readings: readings,
isObligation: isObligation(date: day, title: title),
source: "lokale Berechnung"
)
}
public static func localDays(in range: DayRange) -> [LiturgicalDay] {
DayMath.days(in: range).map(localDay(for:))
}
private static func seasonalSundayRank(for day: Date) -> LiturgicalRank? {
let season = season(for: day)
if season == .advent || season == .christmas || season == .lent || season == .easter {
if season == .lent && DayMath.daysBetween(palmSunday(year: DayMath.year(day)), day) == 0 {
return .feast
}
return .weekday
}
return nil
}
private static func sundayTitle(for day: Date) -> String {
let y = DayMath.year(day)
let season = season(for: day)
switch season {
case .advent:
let start = adventStart(year: y)
let index = DayMath.daysBetween(start, day) / 7 + 1
return ["1. Adventssonntag", "2. Adventssonntag", "3. Adventssonntag", "4. Adventssonntag"].indices.contains(index - 1)
? ["1. Adventssonntag", "2. Adventssonntag", "3. Adventssonntag", "4. Adventssonntag"][index - 1]
: "Adventssonntag"
case .christmas:
let baptism = baptismOfTheLord(year: y)
if DayMath.daysBetween(baptism, day) == 0 {
return "Taufe des Herrn"
}
return "Sonntag in der Weihnachtszeit"
case .lent:
let ash = ashWednesday(year: y)
let index = DayMath.daysBetween(ash, day) / 7 + 1
if index >= 6 { return "Palmsonntag" }
return "\(index). Fastensonntag"
case .easter:
let easter = easterSunday(year: y)
let index = DayMath.daysBetween(easter, day) / 7 + 1
if index == 1 { return "Ostersonntag" }
if index == 8 { return "Pfingsten" }
return "\(index). Sonntag der Osterzeit"
case .ordinary:
return "Sonntag im Jahreskreis"
}
}
private static func weekdayTitle(for day: Date) -> String {
let name = DayMath.weekdayName(day)
switch season(for: day) {
case .advent:
return "\(name) im Advent"
case .christmas:
return "\(name) in der Weihnachtszeit"
case .lent:
return "\(name) in der Fastenzeit"
case .easter:
return "\(name) in der Osterzeit"
case .ordinary:
return "\(name) im Jahreskreis"
}
}
}
+913
View File
@@ -0,0 +1,913 @@
import Foundation
// MARK: - Roles
public enum Role: String, Codable, CaseIterable, Identifiable, Sendable, Hashable {
case lector
case helper
public var id: String { rawValue }
public var title: String {
switch self {
case .lector: "Lektor"
case .helper: "Kommunionhelfer"
}
}
public var plural: String {
switch self {
case .lector: "Lektoren"
case .helper: "Kommunionhelfer"
}
}
public var shortCode: String {
switch self {
case .lector: "L"
case .helper: "K"
}
}
public var symbolName: String {
switch self {
case .lector: "book.closed.fill"
case .helper: "hand.raised.fill"
}
}
}
// MARK: - Church
public enum ChurchSymbol: String, Codable, CaseIterable, Sendable {
case basilica
case gothic
case modern
case rotunda
case roundTower
case chapel
public var caption: String {
switch self {
case .basilica: "Romanische Basilika"
case .gothic: "Neugotische Kirche"
case .modern: "Moderner Kirchenbau"
case .rotunda: "Rundkirche"
case .roundTower: "Rundturm"
case .chapel: "Kapelle"
}
}
}
public struct Church: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var name: String
public var shortName: String
public var symbol: ChurchSymbol
public var colorHex: String
public var address: String
public var sortIndex: Int
public var notes: String
public init(
id: String = UUID().uuidString,
name: String,
shortName: String,
symbol: ChurchSymbol,
colorHex: String,
address: String = "",
sortIndex: Int = 0,
notes: String = ""
) {
self.id = id
self.name = name
self.shortName = shortName
self.symbol = symbol
self.colorHex = colorHex
self.address = address
self.sortIndex = sortIndex
self.notes = notes
}
/// Stable demo identifiers so exported plans remain readable.
public static let andreasID = "church-andreas"
public static let evergislusID = "church-evergislus"
public static let herzJesuID = "church-herz-jesu"
public static let hildegardID = "church-hildegard"
}
// MARK: - People
public struct Person: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var firstName: String
public var lastName: String
public var roles: Set<Role>
public var email: String
public var phone: String
public var preferredChurchIDs: Set<String>
public var preferredWeekdays: Set<Int> // 1 = Sunday … 7 = Saturday; empty = no preference
public var preferredServiceTitles: [String]
public var maxPerMonth: Int
public var active: Bool
public var notes: String
public init(
id: String = UUID().uuidString,
firstName: String,
lastName: String,
roles: Set<Role> = [.lector],
email: String = "",
phone: String = "",
preferredChurchIDs: Set<String> = [],
preferredWeekdays: Set<Int> = [],
preferredServiceTitles: [String] = [],
maxPerMonth: Int = 6,
active: Bool = true,
notes: String = ""
) {
self.id = id
self.firstName = firstName
self.lastName = lastName
self.roles = roles
self.email = email
self.phone = phone
self.preferredChurchIDs = preferredChurchIDs
self.preferredWeekdays = preferredWeekdays
self.preferredServiceTitles = preferredServiceTitles
self.maxPerMonth = maxPerMonth
self.active = active
self.notes = notes
}
public var fullName: String {
"\(firstName) \(lastName)".trimmingCharacters(in: .whitespaces)
}
public var initials: String {
let f = firstName.first.map(String.init) ?? ""
let l = lastName.first.map(String.init) ?? ""
return (f + l).uppercased()
}
public var firstNameWithInitial: String {
guard let initial = lastName.first else { return firstName }
return "\(firstName) \(initial)."
}
public var roleLabel: String {
let ordered = Role.allCases.filter { roles.contains($0) }
return ordered.map(\.title).joined(separator: " · ")
}
public func canFill(_ role: Role) -> Bool { roles.contains(role) }
}
public struct Absence: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var personID: String
public var start: Date
public var end: Date
public var reason: String
public init(
id: String = UUID().uuidString,
personID: String,
start: Date,
end: Date,
reason: String = ""
) {
self.id = id
self.personID = personID
self.start = DayMath.normalize(start)
self.end = DayMath.normalize(end)
self.reason = reason
}
public var range: DayRange { DayRange(start: start, end: end) }
public func overlaps(_ day: Date) -> Bool {
range.contains(day)
}
public var label: String {
let start = DayMath.mediumString(start)
let end = DayMath.mediumString(end)
let base = start == end ? start : "\(start) – \(end)"
return reason.isEmpty ? base : "\(base) · \(reason)"
}
}
// MARK: - Service order
public struct ServiceTemplate: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var churchID: String
public var weekday: Int // 1 = Sunday … 7 = Saturday
public var timeMinutes: Int
public var title: String
public var lectorsNeeded: Int
public var helpersNeeded: Int
public var validFrom: Date
public var validTo: Date?
public var active: Bool
public var notes: String
public init(
id: String = UUID().uuidString,
churchID: String,
weekday: Int,
timeMinutes: Int,
title: String,
lectorsNeeded: Int = 1,
helpersNeeded: Int = 1,
validFrom: Date = DayMath.date(fromKey: "2025-01-01") ?? DayMath.today(),
validTo: Date? = nil,
active: Bool = true,
notes: String = ""
) {
self.id = id
self.churchID = churchID
self.weekday = weekday
self.timeMinutes = timeMinutes
self.title = title
self.lectorsNeeded = lectorsNeeded
self.helpersNeeded = helpersNeeded
self.validFrom = DayMath.normalize(validFrom)
self.validTo = validTo.map(DayMath.normalize)
self.active = active
self.notes = notes
}
public var timeLabel: String { DayMath.timeString(minutes: timeMinutes) }
public var weekdayLabel: String {
let names = ["", "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"]
return names.indices.contains(weekday) ? names[weekday] : "?"
}
public var requirementLabel: String {
var parts: [String] = []
if lectorsNeeded > 0 { parts.append("\(lectorsNeeded)× Lektor") }
if helpersNeeded > 0 { parts.append("\(helpersNeeded)× Kommunionhelfer") }
return parts.isEmpty ? "Keine Dienste" : parts.joined(separator: " · ")
}
public func isValid(on date: Date) -> Bool {
guard active else { return false }
let day = DayMath.normalize(date)
guard DayMath.weekday(day) == weekday else { return false }
guard day >= DayMath.normalize(validFrom) else { return false }
if let validTo, day > DayMath.normalize(validTo) { return false }
return true
}
}
public struct ServiceException: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var templateID: String
public var date: Date
public var reason: String
public init(id: String = UUID().uuidString, templateID: String, date: Date, reason: String = "") {
self.id = id
self.templateID = templateID
self.date = DayMath.normalize(date)
self.reason = reason
}
}
public enum ServiceKind: String, Codable, CaseIterable, Sendable {
case regular
case special
public var title: String {
switch self {
case .regular: "Regulär"
case .special: "Sondergottesdienst"
}
}
}
public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var churchID: String
public var templateID: String?
public var date: Date
public var timeMinutes: Int
public var title: String
public var lectorsNeeded: Int
public var helpersNeeded: Int
public var kind: ServiceKind
public var notes: String
public var locked: Bool
public var createdAt: Date
public init(
id: String = UUID().uuidString,
churchID: String,
templateID: String? = nil,
date: Date,
timeMinutes: Int,
title: String,
lectorsNeeded: Int = 1,
helpersNeeded: Int = 1,
kind: ServiceKind = .regular,
notes: String = "",
locked: Bool = false,
createdAt: Date = Date()
) {
self.id = id
self.churchID = churchID
self.templateID = templateID
self.date = DayMath.normalize(date)
self.timeMinutes = timeMinutes
self.title = title
self.lectorsNeeded = max(0, lectorsNeeded)
self.helpersNeeded = max(0, helpersNeeded)
self.kind = kind
self.notes = notes
self.locked = locked
self.createdAt = createdAt
}
public var timeLabel: String { DayMath.timeString(minutes: timeMinutes) }
public var dateKey: String { DayMath.key(date) }
public var requiredSlots: Int { lectorsNeeded + helpersNeeded }
public var rolesNeeded: [Role] {
var result: [Role] = []
if lectorsNeeded > 0 { result.append(.lector) }
if helpersNeeded > 0 { result.append(.helper) }
return result
}
public func requiredCount(for role: Role) -> Int {
switch role {
case .lector: lectorsNeeded
case .helper: helpersNeeded
}
}
}
public struct Assignment: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var serviceID: String
public var personID: String
public var role: Role
public var locked: Bool
public var note: String
public var createdAt: Date
public init(
id: String = UUID().uuidString,
serviceID: String,
personID: String,
role: Role,
locked: Bool = false,
note: String = "",
createdAt: Date = Date()
) {
self.id = id
self.serviceID = serviceID
self.personID = personID
self.role = role
self.locked = locked
self.note = note
self.createdAt = createdAt
}
}
// MARK: - Liturgy
public enum LiturgicalRank: String, Codable, CaseIterable, Sendable, Comparable {
case weekday = ""
case memorial = "g"
case obligatoryMemorial = "G"
case feast = "F"
case solemnity = "H"
public var label: String {
switch self {
case .weekday: "Wochentag"
case .memorial: "Gedenktag"
case .obligatoryMemorial: "Gebotener Gedenktag"
case .feast: "Fest"
case .solemnity: "Hochfest"
}
}
public var shortLabel: String {
switch self {
case .weekday: ""
case .memorial: "g"
case .obligatoryMemorial: "G"
case .feast: "F"
case .solemnity: "H"
}
}
public var priority: Int {
switch self {
case .weekday: 0
case .memorial: 1
case .obligatoryMemorial: 2
case .feast: 3
case .solemnity: 4
}
}
public var isFeast: Bool { self == .feast || self == .solemnity }
public static func < (lhs: LiturgicalRank, rhs: LiturgicalRank) -> Bool {
lhs.priority < rhs.priority
}
}
public enum LiturgicalColor: String, Codable, CaseIterable, Sendable {
case white = "w"
case red = "r"
case green = "g"
case violet = "v"
case rose = "ros"
case black = "s"
case gold = "gold"
public var label: String {
switch self {
case .white: "Weiß"
case .red: "Rot"
case .green: "Grün"
case .violet: "Violett"
case .rose: "Rosa"
case .black: "Schwarz"
case .gold: "Gold"
}
}
public init(apiValue: String) {
switch apiValue.lowercased() {
case "r": self = .red
case "g": self = .green
case "v": self = .violet
case "ros", "rose": self = .rose
case "s", "sw": self = .black
case "gold": self = .gold
default: self = .white
}
}
}
public enum LiturgicalSeason: String, Codable, CaseIterable, Sendable, Identifiable {
case advent
case christmas
case ordinary
case lent
case easter
public var id: String { rawValue }
public var title: String {
switch self {
case .advent: "Advent"
case .christmas: "Weihnachtszeit"
case .ordinary: "Jahreskreis"
case .lent: "Österliche Bußzeit"
case .easter: "Osterzeit"
}
}
public var shortTitle: String {
switch self {
case .advent: "Advent"
case .christmas: "Weihnachten"
case .ordinary: "Jahreskreis"
case .lent: "Fastenzeit"
case .easter: "Osterzeit"
}
}
public var colorHex: String {
switch self {
case .advent: "#6E4B8E"
case .christmas: "#B58A3B"
case .ordinary: "#4F7D5A"
case .lent: "#75516F"
case .easter: "#C9A227"
}
}
}
public enum FeastSymbol: String, Codable, CaseIterable, Sendable {
case cross
case star
case flame
case sun
case lily
case crown
case heart
case book
case candle
case dove
public var symbolName: String {
switch self {
case .cross: "cross.fill"
case .star: "star.fill"
case .flame: "flame.fill"
case .sun: "sun.max.fill"
case .lily: "leaf.fill"
case .crown: "crown.fill"
case .heart: "heart.fill"
case .book: "book.closed.fill"
case .candle: "sparkles"
case .dove: "bird.fill"
}
}
public var label: String {
switch self {
case .cross: "Kreuz"
case .star: "Stern"
case .flame: "Feuer"
case .sun: "Sonne"
case .lily: "Lilie"
case .crown: "Krone"
case .heart: "Herz"
case .book: "Buch"
case .candle: "Licht"
case .dove: "Taube"
}
}
}
public struct Readings: Codable, Hashable, Sendable {
public var first: String
public var psalm: String
public var second: String
public var gospel: String
public init(first: String = "", psalm: String = "", second: String = "", gospel: String = "") {
self.first = first
self.psalm = psalm
self.second = second
self.gospel = gospel
}
public var isEmpty: Bool {
first.isEmpty && psalm.isEmpty && second.isEmpty && gospel.isEmpty
}
public var shortLabel: String {
var parts: [String] = []
if !first.isEmpty { parts.append(first) }
if !second.isEmpty { parts.append(second) }
if !gospel.isEmpty { parts.append(gospel) }
return parts.joined(separator: " · ")
}
public var fullLabel: String {
var lines: [String] = []
if !first.isEmpty { lines.append("1. Lesung: \(first)") }
if !psalm.isEmpty { lines.append("Psalm: \(psalm)") }
if !second.isEmpty { lines.append("2. Lesung: \(second)") }
if !gospel.isEmpty { lines.append("Evangelium: \(gospel)") }
return lines.joined(separator: "\n")
}
}
public struct LiturgicalDay: Identifiable, Codable, Hashable, Sendable {
public var date: Date
public var title: String
public var rank: LiturgicalRank
public var color: LiturgicalColor
public var remark: String
public var readings: Readings
public var isObligation: Bool
public var source: String
public var updatedAt: Date
public var id: String { DayMath.key(date) }
public var dateKey: String { DayMath.key(date) }
public init(
date: Date,
title: String,
rank: LiturgicalRank = .weekday,
color: LiturgicalColor = .green,
remark: String = "",
readings: Readings = Readings(),
isObligation: Bool = false,
source: String = "eucharistiefeier.de",
updatedAt: Date = Date()
) {
self.date = DayMath.normalize(date)
self.title = title
self.rank = rank
self.color = color
self.remark = remark
self.readings = readings
self.isObligation = isObligation
self.source = source
self.updatedAt = updatedAt
}
public var isSunday: Bool { DayMath.isSunday(date) }
public var isHighFeast: Bool { rank == .solemnity || title.localizedCaseInsensitiveContains("Hochfest") }
public var isFeast: Bool { rank.isFeast || isHighFeast }
public var season: LiturgicalSeason { LiturgicalCalendarEngine.season(for: date) }
public var symbol: FeastSymbol {
LiturgicalCalendarEngine.symbol(for: title, rank: rank, date: date)
}
public var displayTitle: String {
if title.isEmpty {
return isSunday ? "Sonntag" : DayMath.longString(date)
}
return title
}
public var badgeText: String {
if isSunday, isObligation { return "Sonntag" }
if rank != .weekday { return rank.label }
if isObligation { return "Gebotener Feiertag" }
return ""
}
}
// MARK: - Views / statistics support
public struct ServiceWithAssignments: Identifiable, Hashable, Sendable {
public var service: ServiceOccurrence
public var church: Church
public var assignments: [Assignment]
public var id: String { service.id }
public init(service: ServiceOccurrence, church: Church, assignments: [Assignment]) {
self.service = service
self.church = church
self.assignments = assignments
}
public func assignments(for role: Role) -> [Assignment] {
assignments.filter { $0.role == role }
}
public func openSlots(for role: Role) -> Int {
max(0, service.requiredCount(for: role) - assignments(for: role).count)
}
public var filledSlots: Int {
assignments.count
}
public var openSlots: Int {
max(0, service.requiredSlots - assignments.count)
}
public var isFullyStaffed: Bool { openSlots == 0 }
}
public struct DayPlanRow: Identifiable, Hashable, Sendable {
public var date: Date
public var liturgicalDay: LiturgicalDay?
public var services: [ServiceWithAssignments]
public var id: String { DayMath.key(date) }
public init(date: Date, liturgicalDay: LiturgicalDay?, services: [ServiceWithAssignments]) {
self.date = DayMath.normalize(date)
self.liturgicalDay = liturgicalDay
self.services = services
}
public var openSlots: Int { services.reduce(0) { $0 + $1.openSlots } }
public var assignmentCount: Int { services.reduce(0) { $0 + $1.assignments.count } }
public var hasServices: Bool { !services.isEmpty }
}
public struct UnfilledSlot: Identifiable, Hashable, Sendable {
public var service: ServiceOccurrence
public var churchName: String
public var role: Role
public var reason: String
public var id: String { "\(service.id)-\(role.rawValue)" }
}
public struct PersonStat: Identifiable, Hashable, Sendable {
public var person: Person
public var total: Int
public var lectors: Int
public var helpers: Int
public var churchCounts: [String: Int]
public var preferredHits: Int
public var sundayCount: Int
public var lastAssignment: Date?
public var id: String { person.id }
public var preferenceRate: Double {
total == 0 ? 0 : Double(preferredHits) / Double(total)
}
}
public struct ChurchStat: Identifiable, Hashable, Sendable {
public var church: Church
public var assignments: Int
public var services: Int
public var openSlots: Int
public var personCount: Int
public var id: String { church.id }
}
public struct RangeStatistics: Hashable, Sendable {
public var range: DayRange
public var serviceCount: Int
public var assignmentCount: Int
public var openSlots: Int
public var requiredSlots: Int
public var personStats: [PersonStat]
public var churchStats: [ChurchStat]
public var monthlyCounts: [String: Int]
public var sundayServiceCount: Int
public var sundayFilled: Int
public var preferenceHits: Int
public var preferenceEligible: Int
public var absenceDays: Int
public static let empty = RangeStatistics(
range: DayRange(start: DayMath.today(), end: DayMath.today()),
serviceCount: 0,
assignmentCount: 0,
openSlots: 0,
requiredSlots: 0,
personStats: [],
churchStats: [],
monthlyCounts: [:],
sundayServiceCount: 0,
sundayFilled: 0,
preferenceHits: 0,
preferenceEligible: 0,
absenceDays: 0
)
public var coverageRate: Double {
requiredSlots == 0 ? 1 : Double(assignmentCount) / Double(requiredSlots)
}
public var preferenceRate: Double {
preferenceEligible == 0 ? 0 : Double(preferenceHits) / Double(preferenceEligible)
}
public var activePeople: Int { personStats.filter { $0.total > 0 }.count }
public var averageAssignments: Double {
let active = personStats.filter { $0.total > 0 }
guard !active.isEmpty else { return 0 }
return Double(active.reduce(0) { $0 + $1.total }) / Double(active.count)
}
}
// MARK: - Import / export
public enum ExchangeScope: String, Codable, CaseIterable, Sendable {
case resources
case plan
public var title: String {
switch self {
case .resources: "Ressourcen"
case .plan: "Planungsabschnitt"
}
}
}
public struct ResourceBundle: Codable, Hashable, Sendable {
public var churches: [Church]
public var people: [Person]
public var absences: [Absence]
public var templates: [ServiceTemplate]
public var exceptions: [ServiceException]
public init(
churches: [Church] = [],
people: [Person] = [],
absences: [Absence] = [],
templates: [ServiceTemplate] = [],
exceptions: [ServiceException] = []
) {
self.churches = churches
self.people = people
self.absences = absences
self.templates = templates
self.exceptions = exceptions
}
}
public struct PlanExchange: Codable, Sendable {
public var formatVersion: Int
public var exportedAt: Date
public var appName: String
public var scope: ExchangeScope
public var range: DayRange
public var resources: ResourceBundle
public var services: [ServiceOccurrence]
public var assignments: [Assignment]
public var liturgicalDays: [LiturgicalDay]
public var note: String
public init(
formatVersion: Int = 1,
exportedAt: Date = Date(),
appName: String = "LektorenPlan",
scope: ExchangeScope,
range: DayRange,
resources: ResourceBundle,
services: [ServiceOccurrence] = [],
assignments: [Assignment] = [],
liturgicalDays: [LiturgicalDay] = [],
note: String = ""
) {
self.formatVersion = formatVersion
self.exportedAt = exportedAt
self.appName = appName
self.scope = scope
self.range = range
self.resources = resources
self.services = services
self.assignments = assignments
self.liturgicalDays = liturgicalDays
self.note = note
}
public var summary: ExchangeSummary {
ExchangeSummary(
scope: scope,
range: range,
churches: resources.churches.count,
people: resources.people.count,
templates: resources.templates.count,
services: services.count,
assignments: assignments.count,
liturgicalDays: liturgicalDays.count
)
}
}
public struct ExchangeSummary: Hashable, Sendable {
public var scope: ExchangeScope
public var range: DayRange
public var churches: Int
public var people: Int
public var templates: Int
public var services: Int
public var assignments: Int
public var liturgicalDays: Int
}
// MARK: - Planning
public struct PlannerOptions: Codable, Hashable, Sendable {
public var replaceExisting: Bool
public var respectPreferredWeekdays: Bool
public var allowDoubleRolesOnSameDay: Bool
public var weightChurchPreference: Double
public var weightServicePreference: Double
public var weightFairness: Double
public var maxAssignmentsPerDay: Int
public init(
replaceExisting: Bool = false,
respectPreferredWeekdays: Bool = true,
allowDoubleRolesOnSameDay: Bool = false,
weightChurchPreference: Double = 8,
weightServicePreference: Double = 4,
weightFairness: Double = 2.2,
maxAssignmentsPerDay: Int = 1
) {
self.replaceExisting = replaceExisting
self.respectPreferredWeekdays = respectPreferredWeekdays
self.allowDoubleRolesOnSameDay = allowDoubleRolesOnSameDay
self.weightChurchPreference = weightChurchPreference
self.weightServicePreference = weightServicePreference
self.weightFairness = weightFairness
self.maxAssignmentsPerDay = maxAssignmentsPerDay
}
}
public struct PlanResult: Sendable {
public var assignments: [Assignment]
public var unfilled: [UnfilledSlot]
public var filledCount: Int
public var message: String
public init(assignments: [Assignment] = [], unfilled: [UnfilledSlot] = [], filledCount: Int = 0, message: String = "") {
self.assignments = assignments
self.unfilled = unfilled
self.filledCount = filledCount
self.message = message
}
}
+236
View File
@@ -0,0 +1,236 @@
import Foundation
public struct ServicePlanner {
public var people: [Person]
public var absences: [Absence]
public var services: [ServiceOccurrence]
public var existingAssignments: [Assignment]
public var churches: [Church]
public var options: PlannerOptions
public init(
people: [Person],
absences: [Absence],
services: [ServiceOccurrence],
existingAssignments: [Assignment] = [],
churches: [Church] = [],
options: PlannerOptions = PlannerOptions()
) {
self.people = people
self.absences = absences
self.services = services
self.existingAssignments = existingAssignments
self.churches = churches
self.options = options
}
public func plan() -> PlanResult {
let activePeople = people.filter(\.active)
let peopleByID = Dictionary(uniqueKeysWithValues: activePeople.map { ($0.id, $0) })
let absencesByPerson = Dictionary(grouping: absences, by: \.personID)
let churchNames = Dictionary(uniqueKeysWithValues: churches.map { ($0.id, $0.name) })
var working: [Assignment]
if options.replaceExisting {
working = existingAssignments.filter(\.locked)
} else {
working = existingAssignments
}
var totalByPerson: [String: Int] = [:]
var monthByPerson: [String: Int] = [:]
var dayByPerson: [String: Int] = [:]
var churchByPerson: [String: [String: Int]] = [:]
var lastDateByPerson: [String: Date] = [:]
for assignment in working {
guard let service = services.first(where: { $0.id == assignment.serviceID }) else { continue }
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
churchByPerson[assignment.personID, default: [:]][service.churchID, default: 0] += 1
let previous = lastDateByPerson[assignment.personID]
if previous == nil || service.date > previous! {
lastDateByPerson[assignment.personID] = service.date
}
}
let sortedServices = services.sorted {
if $0.date != $1.date { return $0.date < $1.date }
if $0.timeMinutes != $1.timeMinutes { return $0.timeMinutes < $1.timeMinutes }
return $0.id < $1.id
}
var unfilled: [UnfilledSlot] = []
var newAssignments: [Assignment] = []
for service in sortedServices {
for role in Role.allCases {
let required = service.requiredCount(for: role)
guard required > 0 else { continue }
let existingForRole = working.filter { $0.serviceID == service.id && $0.role == role }.count
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,
people: activePeople,
peopleByID: peopleByID,
absencesByPerson: absencesByPerson,
totalByPerson: totalByPerson,
monthByPerson: monthByPerson,
dayByPerson: dayByPerson,
churchByPerson: churchByPerson,
lastDateByPerson: lastDateByPerson,
alreadyAssigned: alreadyAssigned
)
switch result {
case .success(let person):
let assignment = Assignment(
serviceID: service.id,
personID: person.id,
role: role
)
newAssignments.append(assignment)
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
churchByPerson[person.id, default: [:]][service.churchID, default: 0] += 1
lastDateByPerson[person.id] = service.date
case .failure(let reason):
unfilled.append(UnfilledSlot(
service: service,
churchName: churchNames[service.churchID] ?? "",
role: role,
reason: reason
))
}
}
}
}
let filled = newAssignments.count
let message: String
if filled == 0 && unfilled.isEmpty {
message = "Alle Dienste im Zeitraum sind bereits vollständig besetzt."
} else if unfilled.isEmpty {
message = "\(filled) Dienst\(filled == 1 ? "" : "e") erfolgreich besetzt. Alle Lücken geschlossen."
} else {
message = "\(filled) Dienst\(filled == 1 ? "" : "e") besetzt, \(unfilled.count) Lücke\(unfilled.count == 1 ? "" : "n") bleiben offen."
}
if options.replaceExisting {
let locked = working.filter(\.locked)
let combined = locked + newAssignments
return PlanResult(assignments: combined, unfilled: unfilled, filledCount: filled, message: message)
}
return PlanResult(assignments: working, unfilled: unfilled, filledCount: filled, message: message)
}
private enum CandidateResult {
case success(Person)
case failure(String)
}
private func bestCandidate(
for service: ServiceOccurrence,
role: Role,
people: [Person],
peopleByID: [String: Person],
absencesByPerson: [String: [Absence]],
totalByPerson: [String: Int],
monthByPerson: [String: Int],
dayByPerson: [String: Int],
churchByPerson: [String: [String: Int]],
lastDateByPerson: [String: Date],
alreadyAssigned: Set<String>
) -> CandidateResult {
var candidates: [(Person, Double)] = []
var blockedReasons: [String: Int] = [:]
for person in people where person.canFill(role) {
guard !alreadyAssigned.contains(person.id) else {
blockedReasons["bereits im Gottesdienst", default: 0] += 1
continue
}
if let absences = absencesByPerson[person.id], absences.contains(where: { $0.overlaps(service.date) }) {
blockedReasons["abwesend", default: 0] += 1
continue
}
if options.respectPreferredWeekdays,
!person.preferredWeekdays.isEmpty,
!person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
blockedReasons["Einsatztag passt nicht", default: 0] += 1
continue
}
let month = DayMath.monthKey(service.date)
let usedThisMonth = monthByPerson["\(person.id)|\(month)", default: 0]
if person.maxPerMonth > 0, usedThisMonth >= person.maxPerMonth {
blockedReasons["Monatslimit erreicht", default: 0] += 1
continue
}
let usedThisDay = dayByPerson["\(person.id)|\(service.dateKey)", default: 0]
if usedThisDay >= options.maxAssignmentsPerDay {
blockedReasons["bereits an diesem Tag", default: 0] += 1
continue
}
var score = 10.0
if person.preferredChurchIDs.contains(service.churchID) {
score += options.weightChurchPreference
}
if !person.preferredChurchIDs.isEmpty && !person.preferredChurchIDs.contains(service.churchID) {
score -= 1.5
}
if !person.preferredServiceTitles.isEmpty {
let title = service.title.lowercased()
for preference in person.preferredServiceTitles where !preference.isEmpty {
if title.contains(preference.lowercased()) {
score += options.weightServicePreference
}
}
}
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
if let last = lastDateByPerson[person.id] {
let gap = DayMath.daysBetween(last, service.date)
if gap >= 14 { score += 1.8 } else if gap >= 7 { score += 0.8 }
} else {
score += 2.5
}
score += stableTieBreak("\(person.id)|\(service.id)|\(role.rawValue)")
candidates.append((person, score))
}
guard let best = candidates.max(by: { $0.1 < $1.1 }) else {
let reason: String
if blockedReasons.isEmpty {
reason = "Keine geeignete Person mit Rolle \(role.title)"
} else if let top = blockedReasons.max(by: { $0.value < $1.value }) {
reason = "\(top.key) (\(top.value) ausgeschlossen)"
} else {
reason = "Keine geeignete Person"
}
return .failure(reason)
}
return .success(best.0)
}
private func stableTieBreak(_ value: String) -> Double {
var hash = 5381
for byte in value.utf8 {
hash = ((hash << 5) &+ hash) &+ Int(byte)
}
return Double(abs(hash % 997)) / 100_000
}
}
@@ -0,0 +1 @@
{"version":1,"source":"www.eucharistiefeier.de","diocese":"Erzbistum Köln","years":[2025,2026,2027,2028],"days":[{"date":"2025-01-01","title":"1. Januar - Neujahr","rank":"H","color":"w","bem":"Hochfest der Gottesmutter Maria","l1":"Num 6, 22-27","ap":"Ps 67 (66), 2-3.5.6 u. 8 (R: 2a)","l2":"Gal 4, 4-7","ev":"Lk 2, 16-21","obligation":true},{"date":"2025-01-02","title":"Hl. Basilius der Große (379) und hl. Gregor von Nazianz (um 390), Bischöfe, Kirchenlehrer","rank":"G","color":"w","bem":"","l1":"Eph 4, 1-7.11-13","ap":"Ps 23 (22), 1-3.4.5.6 (R: 1)","l2":"","ev":"Mt 23, 8-12","obligation":false},{"date":"2025-01-03","title":"Heiligster Name Jesu","rank":"g","color":"w","bem":"","l1":"Phil 2, 1-11","ap":"Ps 8, 4-5.6-7.8-9 (R: 2a)","l2":"","ev":"Lk 2, 21-24","obligation":false},{"date":"2025-01-04","title":"4. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 3, 7-10","ap":"Ps 98 (97), 1.7-8.9 (R: vgl. 3cd)","l2":"","ev":"Joh 1, 35-42","obligation":false},{"date":"2025-01-05","title":"2. Sonntag nach Weihnachten","rank":"","color":"w","bem":"","l1":"Sir 24, 1-2.8-12 (1-4.12-16)","ap":"Ps 147, 12-13.14-15.19-20 (R: Joh 1, 14)","l2":"Eph 1, 3-6.15-18","ev":"Joh 1, 1-18","obligation":true},{"date":"2025-01-06","title":"Erscheinung des Herrn","rank":"H","color":"w","bem":"","l1":"Jes 60, 1-6","ap":"Ps 72 (71), 1-2.7-8.10-11.12-13 (R: 11)","l2":"Eph 3, 2-3a.5-6","ev":"Mt 2, 1-12","obligation":true},{"date":"2025-01-07","title":"Hl. Raimund von Peñafort, Ordensgründer (1275)","rank":"g","color":"w","bem":"","l1":"2 Kor 5, 14-20","ap":"Ps 103 (102), 1-2.3-4.8-9.13-14.17-18a (R: 11)","l2":"","ev":"Lk 12, 35-40","obligation":false},{"date":"2025-01-08","title":"Hl. Severin, Mönch in Norikum (482)","rank":"g","color":"w","bem":"","l1":"Jak 2, 14-17","ap":"Ps 107 (106), 1-2a u. 3.4-5.6-7.8-9 (R: vgl. Spr 31, 20)","l2":"","ev":"Mt 25, 31-46","obligation":false},{"date":"2025-01-09","title":"9. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 4, 11-18","ap":"Ps 72 (71), 1-2.10-11.12-13 (R: 11)","l2":"","ev":"Mk 6, 45-52","obligation":false},{"date":"2025-01-10","title":"10. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 4, 19 - 5, 4","ap":"Ps 72 (71), 1-2.14 u. 15bc.17 (R: 11)","l2":"","ev":"Lk 4, 14-22a","obligation":false},{"date":"2025-01-11","title":"11. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 5, 5-13","ap":"Ps 147, 12-13.14-15.19-20 (R: 12a)","l2":"","ev":"Lk 5, 12-16","obligation":false},{"date":"2025-01-12","title":"Taufe des Herrn","rank":"F","color":"w","bem":"Sonntag nach dem 6. Januar","l1":"Jes 42, 5a.1-4.6-7 oder Jes 40, 1-5.9-11","ap":"Ps 29 (28), 1-2.3ac-4.3b u. 9b-10 (R: vgl. 11b) oder Ps 104 (103), 1-2.3-4.24-25.27-28.29-30 (R: 1ab)","l2":"Apg 10, 34-38 oder Tit 2, 11-14; 3, 4-7","ev":"Lk 3, 15-16.21-22","obligation":true},{"date":"2025-01-13","title":"Hl. Hilarius, Bischof von Poitiers, Kirchenlehrer (um 367)","rank":"g","color":"w","bem":"","l1":"1 Joh 2, 18-25","ap":"Ps 110 (109), 1-2.3.4-5 (R: 4b)","l2":"","ev":"Mt 5, 13-19","obligation":false},{"date":"2025-01-14","title":"Dienstag der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 2, 5-12","ap":"Ps 8, 2 u. 5.6-7.8-9 (R: vgl. 7)","l2":"","ev":"Mk 1, 21-28","obligation":false},{"date":"2025-01-15","title":"Mittwoch der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 2, 11-12.13c-18","ap":"Ps 105 (104), 1-2.3-4.6-7.8-9 (R: 7a.8a)","l2":"","ev":"Mk 1, 29-39","obligation":false},{"date":"2025-01-16","title":"Donnerstag der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 3, 7-14","ap":"Ps 95 (94), 6-7b.7c-9.10-11 (R: vgl. 7c.8a)","l2":"","ev":"Mk 1, 40-45","obligation":false},{"date":"2025-01-17","title":"Hl. Antonius, Mönchsvater in Ägypten (356)","rank":"G","color":"w","bem":"","l1":"Eph 6, 10-13.18","ap":"Ps 16 (15), 1-2 u. 5.7-8.9 u. 11 (R: vgl. 5a)","l2":"","ev":"Mt 19, 16-26","obligation":false},{"date":"2025-01-18","title":"Samstag der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 4, 12-16","ap":"Ps 19 (18B), 8.9.10.11 u. 15 (R: vgl. Joh 6, 63b)","l2":"","ev":"Mk 2, 13-17","obligation":false},{"date":"2025-01-19","title":"2. Sonntag im Jahreskreis","rank":"","color":"g","bem":"","l1":"Jes 62, 1-5","ap":"Ps 96 (95), 1-2.3-4.6-7.10 (R: vgl. 3a)","l2":"1 Kor 12, 4-11","ev":"Joh 2, 1-11","obligation":true},{"date":"2025-01-20","title":"Hl. Fabian, Papst, Märtyrer (250)","rank":"g","color":"r","bem":"","l1":"1 Petr 5, 1-4","ap":"Ps 40 (39), 2 u. 4ab.7-8.9-10 (R: vgl. 8a.9a)","l2":"","ev":"Joh 21, 1.15-17","obligation":false},{"date":"2025-01-21","title":"Hl. Agnes, Jungfrau, Märtyrin in Rom (304)","rank":"g","color":"r","bem":"","l1":"1 Kor 1, 26-31","ap":"Ps 23 (22), 1-3.4.5.6 (R: 1)","l2":"","ev":"Mt 13, 44-46","obligation":false},{"date":"2025-01-22","title":"Hl. Vinzenz, Diakon, Märtyrer in Spanien (304)","rank":"g","color":"r","bem":"","l1":"2 Kor 4, 7-15","ap":"Ps 34 (33), 2-3.4-5.6-7.8-9 (R: vgl. 5b)","l2":"","ev":"Mt 10, 17-22","obligatioLine truncated
@@ -0,0 +1,221 @@
import Foundation
import SQLite3
private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
public enum SQLiteValue: Sendable, Hashable {
case text(String)
case int(Int)
case double(Double)
case null
public static func bool(_ value: Bool) -> SQLiteValue { .int(value ? 1 : 0) }
public static func dateKey(_ date: Date) -> SQLiteValue { .text(DayMath.key(date)) }
public static func optionalText(_ value: String?) -> SQLiteValue { value.map { .text($0) } ?? .null }
}
public struct SQLiteRow: Sendable {
public let values: [String: SQLiteValue]
public func string(_ key: String) -> String? {
guard case .text(let value)? = values[key] else { return nil }
return value
}
public func string(_ key: String, default defaultValue: String) -> String {
string(key) ?? defaultValue
}
public func int(_ key: String) -> Int? {
switch values[key] {
case .int(let value): return value
case .text(let value): return Int(value)
case .double(let value): return Int(value)
default: return nil
}
}
public func int(_ key: String, default defaultValue: Int) -> Int {
int(key) ?? defaultValue
}
public func double(_ key: String) -> Double? {
switch values[key] {
case .double(let value): return value
case .int(let value): return Double(value)
case .text(let value): return Double(value)
default: return nil
}
}
public func bool(_ key: String, default defaultValue: Bool = false) -> Bool {
guard let value = int(key) else { return defaultValue }
return value != 0
}
public func date(_ key: String) -> Date? {
guard let raw = string(key) else { return nil }
return DayMath.date(fromKey: raw)
}
}
public struct SQLiteError: LocalizedError {
public var message: String
public var code: Int32
public var errorDescription: String? { "SQLite \(code): \(message)" }
}
public final class SQLiteDatabase {
private var handle: OpaquePointer?
private let lock = NSRecursiveLock()
public let path: String
public init(path: String) throws {
self.path = path
var db: OpaquePointer?
let flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX
let result = sqlite3_open_v2(path, &db, flags, nil)
guard result == SQLITE_OK, let db else {
let message = db.map { String(cString: sqlite3_errmsg($0)) } ?? "Unbekannter Fehler"
if let db { sqlite3_close(db) }
throw SQLiteError(message: message, code: result)
}
self.handle = db
sqlite3_busy_timeout(db, 5_000)
if path != ":memory:" {
try execute("PRAGMA journal_mode=WAL;")
}
try execute("PRAGMA foreign_keys=ON;")
try execute("PRAGMA synchronous=NORMAL;")
}
deinit {
if let handle {
sqlite3_close(handle)
}
}
public func execute(_ sql: String) throws {
lock.lock()
defer { lock.unlock() }
guard let handle else { throw SQLiteError(message: "Datenbank geschlossen", code: SQLITE_MISUSE) }
var errorMessage: UnsafeMutablePointer<CChar>?
let result = sqlite3_exec(handle, sql, nil, nil, &errorMessage)
if result != SQLITE_OK {
let message = errorMessage.map { String(cString: $0) } ?? "Unbekannter Fehler"
sqlite3_free(errorMessage)
throw SQLiteError(message: message, code: result)
}
}
public func run(_ sql: String, _ params: [SQLiteValue] = []) throws {
lock.lock()
defer { lock.unlock() }
let statement = try prepare(sql)
defer { sqlite3_finalize(statement) }
try bind(params, to: statement)
let result = sqlite3_step(statement)
guard result == SQLITE_DONE || result == SQLITE_ROW else {
throw currentError(code: result)
}
}
public func query(_ sql: String, _ params: [SQLiteValue] = []) throws -> [SQLiteRow] {
lock.lock()
defer { lock.unlock() }
let statement = try prepare(sql)
defer { sqlite3_finalize(statement) }
try bind(params, to: statement)
var rows: [SQLiteRow] = []
while true {
let result = sqlite3_step(statement)
if result == SQLITE_DONE { break }
guard result == SQLITE_ROW else { throw currentError(code: result) }
var values: [String: SQLiteValue] = [:]
for index in 0..<sqlite3_column_count(statement) {
let name = String(cString: sqlite3_column_name(statement, index))
switch sqlite3_column_type(statement, index) {
case SQLITE_INTEGER:
values[name] = .int(Int(sqlite3_column_int64(statement, index)))
case SQLITE_FLOAT:
values[name] = .double(sqlite3_column_double(statement, index))
case SQLITE_TEXT:
if let text = sqlite3_column_text(statement, index) {
values[name] = .text(String(cString: text))
} else {
values[name] = .null
}
default:
values[name] = .null
}
}
rows.append(SQLiteRow(values: values))
}
return rows
}
public func scalarInt(_ sql: String, _ params: [SQLiteValue] = []) throws -> Int {
guard let row = try query(sql, params).first else { return 0 }
if let value = row.int("value") { return value }
guard case .int(let first)? = row.values.values.first else { return 0 }
return first
}
public var lastInsertRowID: Int64 {
lock.lock()
defer { lock.unlock() }
guard let handle else { return 0 }
return sqlite3_last_insert_rowid(handle)
}
@discardableResult
public func transaction<T>(_ body: () throws -> T) throws -> T {
lock.lock()
defer { lock.unlock() }
try execute("BEGIN IMMEDIATE;")
do {
let value = try body()
try execute("COMMIT;")
return value
} catch {
try? execute("ROLLBACK;")
throw error
}
}
private func prepare(_ sql: String) throws -> OpaquePointer {
guard let handle else { throw SQLiteError(message: "Datenbank geschlossen", code: SQLITE_MISUSE) }
var statement: OpaquePointer?
let result = sqlite3_prepare_v2(handle, sql, -1, &statement, nil)
guard result == SQLITE_OK, let statement else {
throw currentError(code: result)
}
return statement
}
private func bind(_ params: [SQLiteValue], to statement: OpaquePointer) throws {
for (offset, value) in params.enumerated() {
let index = Int32(offset + 1)
let result: Int32
switch value {
case .text(let string):
result = sqlite3_bind_text(statement, index, string, -1, SQLITE_TRANSIENT)
case .int(let int):
result = sqlite3_bind_int64(statement, index, Int64(int))
case .double(let double):
result = sqlite3_bind_double(statement, index, double)
case .null:
result = sqlite3_bind_null(statement, index)
}
guard result == SQLITE_OK else { throw currentError(code: result) }
}
}
private func currentError(code: Int32) -> SQLiteError {
let message = handle.map { String(cString: sqlite3_errmsg($0)) } ?? "Unbekannter Fehler"
return SQLiteError(message: message, code: code)
}
}
+149
View File
@@ -0,0 +1,149 @@
import Foundation
public enum StatisticsCalculator {
public static func compute(
range: DayRange,
services: [ServiceOccurrence],
assignments: [Assignment],
people: [Person],
churches: [Church],
absences: [Absence] = []
) -> RangeStatistics {
let servicesByID = Dictionary(uniqueKeysWithValues: services.map { ($0.id, $0) })
let peopleByID = Dictionary(uniqueKeysWithValues: people.map { ($0.id, $0) })
let assignmentsByPerson = Dictionary(grouping: assignments, by: \.personID)
let assignmentsByService = Dictionary(grouping: assignments, by: \.serviceID)
var personStats: [PersonStat] = people.map { person in
let own = assignmentsByPerson[person.id] ?? []
var lectors = 0
var helpers = 0
var churchCounts: [String: Int] = [:]
var preferredHits = 0
var sundays = 0
var lastDate: Date?
for assignment in own {
guard let service = servicesByID[assignment.serviceID] else { continue }
if assignment.role == .lector { lectors += 1 } else { helpers += 1 }
churchCounts[service.churchID, default: 0] += 1
if DayMath.isSunday(service.date) { sundays += 1 }
if lastDate == nil || service.date > lastDate! { lastDate = service.date }
if preferenceHit(person: person, service: service) { preferredHits += 1 }
}
return PersonStat(
person: person,
total: own.count,
lectors: lectors,
helpers: helpers,
churchCounts: churchCounts,
preferredHits: preferredHits,
sundayCount: sundays,
lastAssignment: lastDate
)
}
personStats.sort {
if $0.total != $1.total { return $0.total > $1.total }
return $0.person.lastName < $1.person.lastName
}
var churchStats: [ChurchStat] = churches.map { church in
let churchServices = services.filter { $0.churchID == church.id }
let serviceIDs = Set(churchServices.map(\.id))
let churchAssignments = assignments.filter { serviceIDs.contains($0.serviceID) }
let open = churchServices.reduce(0) { partial, service in
partial + max(0, service.requiredSlots - (assignmentsByService[service.id]?.count ?? 0))
}
return ChurchStat(
church: church,
assignments: churchAssignments.count,
services: churchServices.count,
openSlots: open,
personCount: Set(churchAssignments.map(\.personID)).count
)
}
churchStats.sort { $0.church.sortIndex < $1.church.sortIndex }
var monthly: [String: Int] = [:]
for assignment in assignments {
guard let service = servicesByID[assignment.serviceID] else { continue }
monthly[DayMath.monthKey(service.date), default: 0] += 1
}
let sundayServices = services.filter { DayMath.isSunday($0.date) }
let sundayServiceIDs = Set(sundayServices.map(\.id))
let sundayFilled = assignments.filter { sundayServiceIDs.contains($0.serviceID) }.count
let requiredSlots = services.reduce(0) { $0 + $1.requiredSlots }
let openSlots = max(0, requiredSlots - assignments.count)
var preferenceHits = 0
var preferenceEligible = 0
for assignment in assignments {
guard let service = servicesByID[assignment.serviceID],
let person = peopleByID[assignment.personID] else { continue }
if hasAnyPreference(person) {
preferenceEligible += 1
if preferenceHit(person: person, service: service) { preferenceHits += 1 }
}
}
let activePeople = Set(people.filter(\.active).map(\.id))
var absenceDays = 0
for absence in absences where activePeople.contains(absence.personID) {
let clamped = absence.range.clamped(to: range)
if clamped.start <= clamped.end { absenceDays += clamped.dayCount }
}
return RangeStatistics(
range: range,
serviceCount: services.count,
assignmentCount: assignments.count,
openSlots: openSlots,
requiredSlots: requiredSlots,
personStats: personStats,
churchStats: churchStats,
monthlyCounts: monthly,
sundayServiceCount: sundayServices.count,
sundayFilled: sundayFilled,
preferenceHits: preferenceHits,
preferenceEligible: preferenceEligible,
absenceDays: absenceDays
)
}
public static func hasAnyPreference(_ person: Person) -> Bool {
!person.preferredChurchIDs.isEmpty || !person.preferredWeekdays.isEmpty || !person.preferredServiceTitles.isEmpty
}
public static func preferenceHit(person: Person, service: ServiceOccurrence) -> Bool {
if person.preferredChurchIDs.contains(service.churchID) { return true }
if person.preferredWeekdays.contains(DayMath.weekday(service.date)) { return true }
let title = service.title.lowercased()
for preference in person.preferredServiceTitles where !preference.isEmpty {
if title.contains(preference.lowercased()) { return true }
}
return false
}
public static func candidateReasons(
person: Person,
service: ServiceOccurrence,
absences: [Absence],
assignments: [Assignment]
) -> [String] {
var reasons: [String] = []
if !person.active { reasons.append("inaktiv") }
if !person.canFill(.lector) && !person.canFill(.helper) { reasons.append("keine Rolle") }
if absences.contains(where: { $0.personID == person.id && $0.overlaps(service.date) }) {
reasons.append("abwesend")
}
if !person.preferredWeekdays.isEmpty && !person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
reasons.append("Einsatztag passt nicht")
}
if assignments.contains(where: { $0.serviceID == service.id && $0.personID == person.id }) {
reasons.append("bereits eingeteilt")
}
return reasons
}
}
+134
View File
@@ -0,0 +1,134 @@
import XCTest
@testable import LektorenPlanCore
final class CoreTests: XCTestCase {
func testEasterDates() {
XCTAssertEqual(DayMath.key(LiturgicalCalendarEngine.easterSunday(year: 2026)), "2026-04-05")
XCTAssertEqual(DayMath.key(LiturgicalCalendarEngine.easterSunday(year: 2027)), "2027-03-28")
XCTAssertEqual(DayMath.key(LiturgicalCalendarEngine.adventStart(year: 2026)), "2026-11-29")
XCTAssertEqual(DayMath.key(LiturgicalCalendarEngine.pentecost(year: 2026)), "2026-05-24")
}
func testLocalCalendarHighFeasts() {
let christmas = LiturgicalCalendarEngine.localDay(for: DayMath.date(fromKey: "2026-12-25")!)
XCTAssertTrue(christmas.isHighFeast)
XCTAssertTrue(christmas.isObligation)
XCTAssertFalse(christmas.readings.isEmpty)
let ordinary = LiturgicalCalendarEngine.localDay(for: DayMath.date(fromKey: "2026-11-10")!)
XCTAssertFalse(ordinary.isObligation)
}
func testDatabaseSeedAndCRUD() throws {
let db = try AppDatabase.makeInMemory(seedDemo: true)
XCTAssertEqual(try db.churches().count, 4)
XCTAssertGreaterThan(try db.services(in: DayRange.year(2026)).count, 300)
XCTAssertNotNil(try db.liturgicalDay(on: DayMath.date(fromKey: "2026-12-25")!))
let person = try XCTUnwrap(try db.person(id: "p-anna"))
XCTAssertTrue(person.roles.contains(.lector))
}
func testPlannerRespectsAbsenceAndFillsSlots() 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 personA = Person(id: "a", firstName: "A", lastName: "A", roles: [.lector], maxPerMonth: 10)
let personB = Person(id: "b", firstName: "B", lastName: "B", roles: [.lector], maxPerMonth: 10)
try db.upsert(personA)
try db.upsert(personB)
let date = DayMath.date(fromKey: "2026-11-08")! // Sunday
try db.upsert(Absence(personID: "a", start: date, end: date, reason: "Test"))
let service = ServiceOccurrence(churchID: "c1", date: date, timeMinutes: 600, title: "Messe", lectorsNeeded: 1, helpersNeeded: 0)
try db.upsert(service)
let planner = ServicePlanner(
people: try db.people(),
absences: try db.absences(),
services: [service],
churches: [church]
)
let result = planner.plan()
XCTAssertEqual(result.filledCount, 1)
XCTAssertEqual(result.assignments.first?.personID, "b")
}
func testExchangeRoundTrip() throws {
let source = try AppDatabase.makeInMemory(seedDemo: true)
let range = DayRange.quarter(containing: DayMath.date(fromKey: "2026-11-07")!)
let exchange = try source.exportPlan(range: range)
XCTAssertGreaterThan(exchange.services.count, 50)
let target = try AppDatabase.makeInMemory(seedDemo: false)
let summary = try target.applyPlanExchange(exchange)
XCTAssertEqual(summary.services, exchange.services.count)
XCTAssertEqual(try target.services(in: range).count, exchange.services.count)
XCTAssertGreaterThan(try target.assignments(in: range).count, 0)
}
func testStatisticsCoherence() throws {
let db = try AppDatabase.makeInMemory(seedDemo: true)
let range = DayRange.quarter(containing: DayMath.date(fromKey: "2026-11-07")!)
let services = try db.services(in: range)
let assignments = try db.assignments(in: range)
let stats = StatisticsCalculator.compute(
range: range,
services: services,
assignments: assignments,
people: try db.people(),
churches: try db.churches(),
absences: try db.absences()
)
XCTAssertEqual(stats.assignmentCount, assignments.count)
XCTAssertLessThanOrEqual(stats.openSlots, stats.requiredSlots)
XCTAssertEqual(stats.churchStats.reduce(0) { $0 + $1.services }, services.count)
}
func testDemoCoverage() throws {
let db = try AppDatabase.makeInMemory(seedDemo: true)
for label in ["Q4 2026", "2026", "2025"] {
let range: DayRange
if label == "Q4 2026" { range = DayRange.quarter(containing: DayMath.date(fromKey: "2026-11-07")!) }
else if label == "2026" { range = DayRange.year(2026) }
else { range = DayRange.year(2025) }
let stats = StatisticsCalculator.compute(
range: range,
services: try db.services(in: range),
assignments: try db.assignments(in: range),
people: try db.people(),
churches: try db.churches(),
absences: try db.absences()
)
print("DEMO \(label): services=\(stats.serviceCount) required=\(stats.requiredSlots) assigned=\(stats.assignmentCount) open=\(stats.openSlots) coverage=\(String(format: "%.1f", stats.coverageRate * 100))% preference=\(String(format: "%.1f", stats.preferenceRate * 100))%")
}
}
func testRangeLabelsAndPreferenceRate() {
let range = DayRange(
start: DayMath.date(fromKey: "2026-10-01")!,
end: DayMath.date(fromKey: "2026-12-31")!
)
XCTAssertEqual(range.shortTitle, "1. Okt. – 31. Dez. 2026")
var stats = RangeStatistics.empty
stats.assignmentCount = 10
stats.preferenceHits = 3
stats.preferenceEligible = 4
XCTAssertEqual(stats.preferenceRate, 0.75, accuracy: 0.0001)
stats.preferenceEligible = 0
XCTAssertEqual(stats.preferenceRate, 0)
}
func testAPIParsing() throws {
let json = """
{"Kalendername":"Test","Zelebrationen":{
"a":{"Datum":"2026-12-25","Tl":"Weihnachten","Rang":"H","Farbe":"w","L1":"Jes 52","EV":"Joh 1","Bem":"Am Tag"},
"b":{"Datum":"2026-12-25","Tl":"Weihnachten","Rang":"H","Farbe":"w","L1":"Jes 9","EV":"Lk 2","Bem":"In der Heiligen Nacht"}
}}
""".data(using: .utf8)!
let days = try LiturgicalCalendarAPI.parse(data: json, year: 2026)
let christmas = try XCTUnwrap(days.first { $0.dateKey == "2026-12-25" })
XCTAssertEqual(christmas.title, "Weihnachten")
XCTAssertEqual(christmas.readings.gospel, "Joh 1")
XCTAssertTrue(christmas.isObligation)
}
}
+25
View File
@@ -0,0 +1,25 @@
Erstelle ein neues macOS-SwiftUI-Projekt namens ‚LektorenPlan‘ mit einem modernen Interface.
In der Hauptansicht soll sie in einer Tabellenstruktur einen Kalenderanzeigen, bei dem jede Zeile einem Tag entspricht. Die Sonntage und katholischen Feiertage werden grafisch hervorgehoben.
Die Aufgabe besteht darin, für wiederkehrende Gottesdienste an bestimmten katholischen Kirchen im Pfarrgebiet von Bad Godesberg die Besetzung mit Lektoren und Kommunionhelfern zu planen.
Die Kirchen sind: St. Andreas, St. Evergislus, Herz Jesu, St. Hildegard.
Planungsgrundlage ist eine Gottesdienstordnung, die die regelmäßigen Gottesdienstzeiten an den verschiednen Kirchen ebenso berücksichtigen muss wie die Besonderheiten des Kirchenjahres
mit dem liturgischen Kalender für das Erzbistum Köln, der auch aus dem Internet aktualisiert werden kann: API über www.eucharistiefeier.de.
Als Hilfestellung für die Lektoren sollen die Lesungen des Tages genannt werden.
Die Planung besteht darin, jeden Lektor und Kommunionhelfer (kann auch eine Person sein) unter Berücksichtigung dessen individueller Ausschlusstermine und Vorlieben von Orten und Gottesdiensten auf die Gottesdienste zu verteilen.
Die Planung bezieht sich dabei immer auf einen bestimmten Abschnitt im Jahr,
die Anwendung kann aber über die bisherige und künftige Planung Visualisierungen und statistische Auswertungen für beliebige Zeitfenster machen.
Daher soll die Auswahl des Zeitfensters über eine eigene geeignete UI-Komponente (z.B. eine Art Zeitstrahl mit beweglichem Schiebern für Anfang und Ende) oder Auswahl von markanten Zeitmarken wie Quartale, Jahresende, Ende der Oster- oder Weihnachstzeit,... möglich sein.
Dabei soll auch immer eine Statstik über die Einsatzhäufigkeit, die Verteilung auf die Orte, die Berücksichtigung von Vorlieben etc visualisierbar sein.
Die Planung soll unterstützt werden durch Übernahme der Gottesdienstordnung, Verwaltung der Ressourcen und Visualisierung von noch zu planenden Gottesdiensten.
Das alles soll in einer sqlite Datenbank persistiert werden.
Es gibt eine Import/Export Schnitstelle, um einen Planungsabschnitt oder Ressourcen zwischen zwei Anwendungsorten austauschen zu können.
Das Ergbebnis einer Planung für einen Zeitabschnitt (z.B. Quartal eines Jahres) soll in Form eines PDF Dokuments präsentiert werden können oder direkt aus der Anwendung ausdruckbar sein.
Planungsvorgaben für die Ressourcen sollen in geeigneten Dialogen erfolgen:
- Verwaltung der Gottesdienstordnung einschließlich der Sonderbehandlung von Festen oder Sonderereignissen
- Verwaltung der Lektoren und Kommunionhelfer mit bevorzugten Einsatzorten, bevorzugten Gottesdiensten, Einsatztage, Abwesenheiten
Das User Interface soll einfachen und modernen Bedienkonzepten folgen. Wo immer möglich soll die Hintergrundinformation zur Befüllung des liturgischen Kalenders durch Internetrecherche ermöglicht werden.
Die Visualisierung soll grafisch eingängig sein. So sollten beispielsweise Kirchen durch symbolische Strichzeichnungen vereinfacht erkennbar sein und Texte erst beim Hovern der Maus lesbar werden.
Ebenso können durch eindeutige Symbole bestimmte Hochfeste hervorgehoben werden.
Erstelle ein Grobkonzept und einen ersten Prototypen.