UI verbessert, 2. PDF als kompakte Variante

This commit is contained in:
concierge committed 2026-11-12 19:59:51 +01:00
1 parent 1bf3283029
commit f9e3e94629
23 files changed
+1009 -146

No files matched your search

@@ -7,14 +7,21 @@ struct TimelineRangePicker: View {
@State private var draftEnd = DayMath.today()
@State private var initialized = false
@State private var dragOrigin: DayRange?
@State private var dragBounds: DayRange?
@State private var zoom: Double = 1
@State private var viewportCenter: Date?
@State private var startCalendarVisible = false
@State private var endCalendarVisible = false
private let minDays = 7
var body: some View {
let bounds = timelineBounds
VStack(spacing: 12) {
header(bounds: bounds)
timeline(bounds: bounds)
let fullBounds = calendarBounds
let visible = dragBounds ?? visibleBounds(in: fullBounds)
VStack(spacing: 10) {
header(bounds: fullBounds)
rangeControls
timeline(bounds: visible)
.frame(height: 64)
footer
}
@@ -33,15 +40,21 @@ struct TimelineRangePicker: View {
guard !initialized else { return }
draftStart = model.range.start
draftEnd = model.range.end
viewportCenter = midpoint(draftRange)
initialized = true
}
.onChange(of: model.range) { _, newValue in
draftStart = newValue.start
draftEnd = newValue.end
viewportCenter = midpoint(newValue)
}
.onChange(of: zoom) { _, _ in
dragBounds = nil
viewportCenter = midpoint(draftRange)
}
}
private var timelineBounds: DayRange {
private var calendarBounds: DayRange {
let currentYear = DayMath.year(DayMath.today())
let firstYear = min(currentYear - 1, DayMath.year(draftStart) - 1)
let lastYear = max(currentYear + 2, DayMath.year(draftEnd) + 1)
@@ -50,6 +63,31 @@ struct TimelineRangePicker: View {
return DayRange(start: start, end: end)
}
private func visibleBounds(in full: DayRange) -> DayRange {
guard zoom > 1.01 else { return full }
let center = viewportCenter ?? midpoint(draftRange)
let selectionDays = max(1, draftRange.dayCount)
let idealSpan = Int((Double(max(1, full.dayCount)) / zoom).rounded())
let span = min(full.dayCount, max(minDays + 14, max(selectionDays + 28, idealSpan)))
var start = DayMath.adding(days: -(span / 2), to: center)
var end = DayMath.adding(days: span - 1, to: start)
if start < full.start {
start = full.start
end = DayMath.adding(days: span - 1, to: start)
}
if end > full.end {
end = full.end
start = DayMath.adding(days: -(span - 1), to: end)
}
if start < full.start { start = full.start }
return DayRange(start: start, end: end)
}
private func midpoint(_ range: DayRange) -> Date {
let days = max(0, DayMath.daysBetween(range.start, range.end))
return DayMath.adding(days: days / 2, to: range.start)
}
private func header(bounds: DayRange) -> some View {
HStack(alignment: .center, spacing: 12) {
HStack(spacing: 7) {
@@ -123,6 +161,151 @@ struct TimelineRangePicker: View {
}
}
private var rangeControls: some View {
HStack(spacing: 10) {
dateField(
label: "Beginn",
date: draftStart,
selection: startBinding,
isPresented: $startCalendarVisible
)
Text("bis")
.font(.system(size: 9.5, weight: .medium, design: .rounded))
.foregroundStyle(LP.inkTertiary)
dateField(
label: "Ende",
date: draftEnd,
selection: endBinding,
isPresented: $endCalendarVisible
)
Spacer(minLength: 12)
zoomControl
}
}
private func dateField(
label: String,
date: Date,
selection: Binding<Date>,
isPresented: Binding<Bool>
) -> some View {
Button {
isPresented.wrappedValue.toggle()
} label: {
HStack(spacing: 6) {
Text(label)
.font(.system(size: 9, weight: .semibold, design: .rounded))
.foregroundStyle(LP.inkTertiary)
Text(DayMath.mediumString(date))
.font(.system(size: 10, weight: .medium))
.foregroundStyle(LP.ink)
.monospacedDigit()
Image(systemName: "calendar")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.accent)
}
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.7))
}
.buttonStyle(.plain)
.popover(isPresented: isPresented, arrowEdge: .bottom) {
VStack(alignment: .leading, spacing: 8) {
Text(label)
.font(.system(size: 10, weight: .bold, design: .rounded))
.foregroundStyle(LP.inkSecondary)
DatePicker("", selection: selection, displayedComponents: .date)
.datePickerStyle(.graphical)
.labelsHidden()
.onChange(of: selection.wrappedValue) { _, _ in
isPresented.wrappedValue = false
}
}
.padding(12)
}
.help("\(label) über den Kalender wählen")
}
private var startBinding: Binding<Date> {
Binding(
get: { draftStart },
set: { newValue in
let maxStart = DayMath.adding(days: -(minDays - 1), to: draftEnd)
let clamped = min(max(DayMath.normalize(newValue), calendarBounds.start), maxStart)
draftStart = clamped
viewportCenter = midpoint(draftRange)
model.setRange(draftRange)
}
)
}
private var endBinding: Binding<Date> {
Binding(
get: { draftEnd },
set: { newValue in
let minEnd = DayMath.adding(days: minDays - 1, to: draftStart)
let clamped = max(min(DayMath.normalize(newValue), calendarBounds.end), minEnd)
draftEnd = clamped
viewportCenter = midpoint(draftRange)
model.setRange(draftRange)
}
)
}
private var zoomControl: some View {
HStack(spacing: 6) {
Button {
zoom = max(1, zoom - 1)
} label: {
Image(systemName: "minus.magnifyingglass")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
}
.buttonStyle(.plain)
.help("Herauszoomen")
.disabled(zoom <= 1.01)
Slider(value: $zoom, in: 1...16, step: 0.5)
.tint(LP.accent)
.frame(width: 110)
Button {
zoom = min(16, zoom + 1)
} label: {
Image(systemName: "plus.magnifyingglass")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
}
.buttonStyle(.plain)
.help("Hineinzoomen")
.disabled(zoom >= 15.99)
Text(String(format: "%.1f×", zoom))
.font(.system(size: 9, weight: .semibold, design: .rounded))
.foregroundStyle(LP.inkSecondary)
.frame(width: 32, alignment: .trailing)
.monospacedDigit()
Button {
zoom = 1
} label: {
Image(systemName: "arrow.counterclockwise")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
}
.buttonStyle(.plain)
.help("Zoom zurücksetzen")
.disabled(zoom <= 1.01)
}
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.cardMuted))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.6), lineWidth: 0.7))
.help("Globale Zeitskala zoomen")
}
private func timeline(bounds: DayRange) -> some View {
GeometryReader { geo in
let width = geo.size.width
@@ -179,8 +362,8 @@ struct TimelineRangePicker: View {
}
}
// Month labels around selection
if width > 500 {
// Date labels around selection (only when they do not overlap)
if width > 500, xEnd - xStart >= 120 {
Text(DayMath.mediumString(draftStart))
.font(.system(size: 9, weight: .semibold, design: .rounded))
.foregroundStyle(LP.accent)
@@ -226,7 +409,7 @@ struct TimelineRangePicker: View {
Text("\(Int(model.stats.coverageRate * 100)) % besetzt")
.foregroundStyle(model.stats.openSlots == 0 ? LP.success : LP.open)
Spacer()
Text("Ziehen oder Zeitmarke wählen")
Text("Ziehen, zoomen oder Datum wählen")
.foregroundStyle(LP.inkTertiary)
}
.font(.system(size: 9.5, weight: .medium, design: .rounded))
@@ -275,6 +458,8 @@ struct TimelineRangePicker: View {
.opacity(0.5)
}
.shadow(color: color.opacity(0.35), radius: 4, y: 2)
.frame(width: 24, height: 48)
.contentShape(Rectangle())
.help(help)
}
@@ -285,6 +470,7 @@ struct TimelineRangePicker: View {
.onChanged { value in
if dragOrigin == nil {
dragOrigin = DayRange(start: draftStart, end: draftEnd)
dragBounds = bounds
}
guard let origin = dragOrigin else { return }
let dayDelta = Int((value.translation.width / max(1, width)) * totalDays)
@@ -304,6 +490,8 @@ struct TimelineRangePicker: View {
}
.onEnded { _ in
dragOrigin = nil
dragBounds = nil
viewportCenter = midpoint(draftRange)
model.setRange(draftRange)
}
}
+12 -4
View File
@@ -43,14 +43,22 @@ struct AppCommands: Commands {
}
.keyboardShortcut("i", modifiers: [.command, .shift])
Divider()
Button("PDF-Vorschau…") {
model.createPDFPreview()
Button("PDF-Vorschau (übersichtlich)…") {
model.createPDFPreview(variant: .full)
}
.keyboardShortcut("p", modifiers: [.command, .shift])
Button("Drucken…") {
model.printPDF()
Button("PDF-Vorschau (kompakte Liste)…") {
model.createPDFPreview(variant: .compact)
}
.keyboardShortcut("l", modifiers: [.command, .shift])
Button("Drucken (übersichtlich)…") {
model.printPDF(variant: .full)
}
.keyboardShortcut("p", modifiers: .command)
Button("Drucken (kompakte Liste)…") {
model.printPDF(variant: .compact)
}
.keyboardShortcut("p", modifiers: [.command, .option])
}
CommandMenu("Planung") {
@@ -260,6 +260,7 @@ enum PlanPDFRenderer {
var height: CGFloat = 5
for service in services {
height += 12
if service.service.location != nil { height += 9 }
for role in Role.allCases where service.service.requiredCount(for: role) > 0 {
height += 9
}
@@ -373,6 +374,17 @@ enum PlanPDFRenderer {
)
serviceY += 11
if let location = service.service.location {
drawText(
location,
in: CGRect(x: x + 7, y: serviceY, width: churchWidth - 12, height: 9),
font: sans(6.5, weight: .medium),
color: burgundy,
maxLines: 1
)
serviceY += 9
}
for role in Role.allCases where service.service.requiredCount(for: role) > 0 {
let names = service.assignments(for: role).compactMap { people[$0.personID]?.fullName }
let prefix = role == .lector ? "L" : "K"
+150 -35
View File
@@ -111,6 +111,26 @@ struct PDFPreview: Identifiable {
var data: Data
var title: String
var filename: String
var formatLabel: String
}
enum PlanPDFVariant {
case full
case compact
var formatLabel: String {
switch self {
case .full: "A4 quer · Kirchenspalten"
case .compact: "A4 hoch · kompakte Liste"
}
}
var filenameComponent: String {
switch self {
case .full: "Plan"
case .compact: "Liste"
}
}
}
struct CandidateSuggestion: Identifiable {
@@ -162,6 +182,7 @@ final class PlanModel: ObservableObject {
@Published var pdfPreview: PDFPreview?
@Published var databasePath: String
@Published var startupWarning: String?
@Published var isResettingData = false
private var toastTask: Task<Void, Never>?
@@ -302,6 +323,8 @@ final class PlanModel: ObservableObject {
if row.liturgicalDay?.readings.shortLabel.lowercased().contains(query) == true { return true }
for service in row.services {
if service.church.name.lowercased().contains(query) { return true }
if let location = service.service.location,
location.lowercased().contains(query) { return true }
if service.service.title.lowercased().contains(query) { return true }
for assignment in service.assignments {
if let person = peopleByID[assignment.personID],
@@ -418,26 +441,47 @@ final class PlanModel: ObservableObject {
}
}
func candidateSuggestions(for service: ServiceOccurrence, role: Role) -> [CandidateSuggestion] {
func candidateSuggestions(
for service: ServiceOccurrence,
role: Role,
ignorePreferredWeekdays: Bool = false
) -> [CandidateSuggestion] {
let rangeAssignments = assignments
let monthKey = DayMath.monthKey(service.date)
let serviceDateByID = Dictionary(uniqueKeysWithValues: services.map { ($0.id, $0) })
var monthlyCounts: [String: Int] = [:]
var totalCounts: [String: Int] = [:]
var dayCounts: [String: Int] = [:]
var dayServices: [String: Set<String>] = [:]
for assignment in rangeAssignments {
guard let assignedService = serviceDateByID[assignment.serviceID] else { continue }
monthlyCounts["\(assignment.personID)|\(DayMath.monthKey(assignedService.date))", default: 0] += 1
totalCounts[assignment.personID, default: 0] += 1
dayCounts["\(assignment.personID)|\(assignedService.dateKey)", default: 0] += 1
dayServices["\(assignment.personID)|\(assignedService.dateKey)", default: []].insert(assignment.serviceID)
}
let assignedToService = Set(assignments.filter { $0.serviceID == service.id }.map(\.personID))
// Lector and helper do not exclude each other: a person may be suggested
// for the complementary role even when already serving this service.
// Read the service assignments directly so this also works when the
// service is outside the currently loaded range.
let serviceAssignments = (try? db.assignments(serviceIDs: [service.id]))
?? assignments.filter { $0.serviceID == service.id }
var assignedRolesByPerson: [String: Set<Role>] = [:]
for assignment in serviceAssignments {
assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role)
}
let weekday = DayMath.weekday(service.date)
return people
.filter { $0.active && $0.canFill(role) && !assignedToService.contains($0.id) }
let eligiblePeople = people.filter { person in
guard person.active, person.canFill(role) else { return false }
return !(assignedRolesByPerson[person.id]?.contains(role) ?? false)
}
// Only prefer a dual-role assignment while the person is not already
// noticeably ahead of others. Otherwise fairness wins.
let minimumTotal = eligiblePeople.map { totalCounts[$0.id, default: 0] }.min() ?? 0
let fairnessSlack = 1
return eligiblePeople
.map { person in
var warnings: [String] = []
var blocked = false
@@ -445,7 +489,9 @@ final class PlanModel: ObservableObject {
warnings.append("abwesend")
blocked = true
}
if !person.preferredWeekdays.isEmpty && !person.preferredWeekdays.contains(weekday) {
if !ignorePreferredWeekdays,
!person.preferredWeekdays.isEmpty,
!person.preferredWeekdays.contains(weekday) {
warnings.append("Einsatztag passt nicht")
blocked = true
}
@@ -453,12 +499,24 @@ final class PlanModel: ObservableObject {
warnings.append("Monatslimit")
blocked = true
}
if dayCounts["\(person.id)|\(service.dateKey)", default: 0] > 0 {
let servicesThisDay = dayServices["\(person.id)|\(service.dateKey)", default: []]
if !servicesThisDay.isEmpty, !servicesThisDay.isSubset(of: [service.id]) {
warnings.append("bereits an diesem Tag")
blocked = true
}
let total = totalCounts[person.id, default: 0]
let withinFairnessReach = total - minimumTotal <= fairnessSlack
var score = 0.0
var preferred = false
if withinFairnessReach, assignedRolesByPerson[person.id]?.contains(role.complementary) == true {
score += 14
preferred = true
} else if withinFairnessReach,
service.rolesNeeded.count > 1,
person.roles.contains(where: { $0 != role && service.requiredCount(for: $0) > 0 }) {
score += 14
preferred = true
}
if person.preferredChurchIDs.contains(service.churchID) {
score += 8
preferred = true
@@ -476,7 +534,7 @@ final class PlanModel: ObservableObject {
preferred = true
}
}
score -= Double(totalCounts[person.id, default: 0]) * 1.4
score -= Double(total) * 1.4
if absences.contains(where: { $0.personID == person.id && $0.overlaps(service.date) }) {
score -= 100
}
@@ -780,18 +838,32 @@ final class PlanModel: ObservableObject {
// MARK: - PDF & print
func createPDFPreview() {
let data = PlanPDFRenderer.render(
range: range,
rows: rows,
churches: churches,
people: peopleByID,
generatedAt: Date()
)
func createPDFPreview(variant: PlanPDFVariant = .full) {
let data: Data
switch variant {
case .full:
data = PlanPDFRenderer.render(
range: range,
rows: rows,
churches: churches,
people: peopleByID,
generatedAt: Date()
)
case .compact:
data = CompactPlanPDFRenderer.render(
range: range,
rows: rows,
people: peopleByID,
generatedAt: Date()
)
}
pdfPreview = PDFPreview(
data: data,
title: "Lektorenplan \(range.shortTitle)",
filename: "LektorenPlan_\(DayMath.key(range.start))_\(DayMath.key(range.end)).pdf"
title: variant == .compact
? "Gottesdienstliste \(range.shortTitle)"
: "Lektorenplan \(range.shortTitle)",
filename: "LektorenPlan_\(variant.filenameComponent)_\(DayMath.key(range.start))_\(DayMath.key(range.end)).pdf",
formatLabel: variant.formatLabel
)
}
@@ -811,21 +883,34 @@ final class PlanModel: ObservableObject {
}
}
func printPDF(data: Data? = nil) {
let pdfData = data ?? PlanPDFRenderer.render(
range: range,
rows: rows,
churches: churches,
people: peopleByID,
generatedAt: Date()
)
func printPDF(data: Data? = nil, variant: PlanPDFVariant = .full) {
let pdfData = data ?? {
switch variant {
case .full:
return PlanPDFRenderer.render(
range: range,
rows: rows,
churches: churches,
people: peopleByID,
generatedAt: Date()
)
case .compact:
return CompactPlanPDFRenderer.render(
range: range,
rows: rows,
people: peopleByID,
generatedAt: Date()
)
}
}()
guard let document = PDFDocument(data: pdfData) else {
alertTitle = "Drucken nicht möglich"
alertMessage = "Das PDF konnte nicht erzeugt werden."
return
}
let info = NSPrintInfo.shared.copy() as? NSPrintInfo ?? NSPrintInfo.shared
info.orientation = .landscape
let bounds = document.page(at: 0)?.bounds(for: .mediaBox) ?? .zero
info.orientation = bounds.width > bounds.height ? .landscape : .portrait
info.topMargin = 0
info.bottomMargin = 0
info.leftMargin = 0
@@ -840,13 +925,43 @@ final class PlanModel: ObservableObject {
// MARK: - Demo
func resetDemoData() {
do {
try db.resetDemoData()
loadAll()
showToast("Demo-Daten neu aufgebaut.", kind: .success)
} catch {
alertTitle = "Demo-Daten konnten nicht zurückgesetzt werden"
alertMessage = error.localizedDescription
rebuildContent(deleteOnly: false)
}
func deleteAllData() {
rebuildContent(deleteOnly: true)
}
private func rebuildContent(deleteOnly: Bool) {
guard !isResettingData else { return }
isResettingData = true
let database = db
Task {
do {
try await Task.detached(priority: .userInitiated) {
if deleteOnly {
try database.deleteAllData()
} else {
try database.resetDemoData()
}
}.value
range = .quarter(containing: DayMath.today())
db.setSetting("rangeStart", value: DayMath.key(range.start))
db.setSetting("rangeEnd", value: DayMath.key(range.end))
loadAll()
isResettingData = false
showToast(
deleteOnly ? "Alle Daten wurden gelöscht." : "Demo-Daten neu aufgebaut.",
kind: .success
)
} catch {
isResettingData = false
alertTitle = deleteOnly
? "Daten konnten nicht gelöscht werden"
: "Demo-Daten konnten nicht zurückgesetzt werden"
alertMessage = error.localizedDescription
}
}
}
+1 -1
View File
@@ -226,7 +226,7 @@ private struct SidebarView: View {
.foregroundStyle(LP.inkTertiary.opacity(0.85))
.underline()
}
Text("Prototyp 0.1 · Erzbistum Köln")
Text("Version \(AppMetadata.version) · Erzbistum Köln")
.font(.system(size: 7.5, weight: .regular))
.foregroundStyle(LP.inkTertiary.opacity(0.7))
}
+47 -8
View File
@@ -11,18 +11,57 @@ enum SnapshotCapture {
let environment = ProcessInfo.processInfo.environment
let wantsSnapshot = environment["LP_SNAPSHOT"] != nil
let wantsPDF = environment["LP_PDF"] != nil
let resetReportPath = environment["LP_RESET_DEMO"]
guard wantsSnapshot || wantsPDF || resetReportPath != nil else { return }
if let resetReportPath {
// End-to-end check of the settings recovery flow: run the real model
// action, wait until the async rebuild finishes, then report counts.
switch environment["LP_RESET_MODE"] {
case "delete":
model.deleteAllData()
case "none":
break
default:
model.resetDemoData()
}
let deadline = Date().addingTimeInterval(60)
while model.isResettingData && Date() < deadline {
try? await Task.sleep(nanoseconds: 100_000_000)
}
let report = """
churches=\(model.churches.count)
people=\(model.people.count)
services=\(model.services.count)
isResetting=\(model.isResettingData)
alert=\(model.alertMessage ?? "none")
"""
try? report.write(toFile: resetReportPath, atomically: true, encoding: .utf8)
NSApplication.shared.terminate(nil)
return
}
guard wantsSnapshot || wantsPDF else { return }
try? await Task.sleep(nanoseconds: 1_500_000_000)
if let pdfPath = environment["LP_PDF"] {
let data = PlanPDFRenderer.render(
range: model.range,
rows: model.rows,
churches: model.churches,
people: model.peopleByID,
generatedAt: Date()
)
let data: Data
if environment["LP_PDF_VARIANT"] == "compact" {
data = CompactPlanPDFRenderer.render(
range: model.range,
rows: model.rows,
people: model.peopleByID,
generatedAt: Date()
)
} else {
data = PlanPDFRenderer.render(
range: model.range,
rows: model.rows,
churches: model.churches,
people: model.peopleByID,
generatedAt: Date()
)
}
try? data.write(to: URL(fileURLWithPath: pdfPath))
}
+1 -1
View File
@@ -274,7 +274,7 @@ struct PersonMiniChip: View {
var body: some View {
HStack(spacing: 4) {
Avatar(initials: person.initials, color: color, size: 18)
Text(person.firstNameWithInitial)
Text(person.abbreviatedName)
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
.lineLimit(1)
@@ -28,7 +28,7 @@ struct PDFPreviewSheet: View {
Text(preview.title)
.font(LP.serifHeadline)
.foregroundStyle(LP.ink)
Text("\(document?.pageCount ?? 0) Seiten · A4 quer · bereit zum Drucken")
Text("\(document?.pageCount ?? 0) Seiten · \(preview.formatLabel) · bereit zum Drucken")
.font(.system(size: 10))
.foregroundStyle(LP.inkSecondary)
}
+63 -30
View File
@@ -54,9 +54,14 @@ struct PlanningView: View {
.disabled(model.isSyncing)
SecondaryActionButton(title: "PDF", icon: "doc.richtext") {
model.createPDFPreview()
model.createPDFPreview(variant: .full)
}
.help("Planung als PDF ansehen, sichern oder drucken")
.help("Übersichtlichen Plan als PDF ansehen, sichern oder drucken (A4 quer)")
SecondaryActionButton(title: "Liste", icon: "list.bullet.rectangle") {
model.createPDFPreview(variant: .compact)
}
.help("Kompakte Gottesdienstliste als PDF ansehen, sichern oder drucken (A4 hoch)")
Menu {
Button {
@@ -164,39 +169,50 @@ private struct CalendarTable: View {
let minimum = horizontalPadding * 2 + dateWidth + liturgyWidth + churchMinWidth * 4 + gap * 5
let width = max(geo.size.width, minimum)
let churchWidth = (width - horizontalPadding * 2 - dateWidth - liturgyWidth - gap * 5) / 4
ScrollView(.horizontal, showsIndicators: false) {
VStack(spacing: 0) {
columnHeader(churchWidth: churchWidth)
Hairline()
if model.filteredRows.isEmpty {
EmptyStateView(
icon: "calendar",
title: "Keine Tage im Filter",
message: "Für diesen Zeitraum und Filter sind keine Einträge vorhanden."
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ScrollView(.vertical) {
LazyVStack(spacing: 0, pinnedViews: []) {
ForEach(monthGroups) { group in
monthHeader(group, churchWidth: churchWidth)
ForEach(group.rows) { row in
DayRow(
row: row,
churchWidth: churchWidth,
dateWidth: dateWidth,
liturgyWidth: liturgyWidth,
gap: gap,
horizontalPadding: horizontalPadding
)
if model.churches.isEmpty {
EmptyStateView(
icon: "building.columns",
title: "Keine Daten vorhanden",
message: "Es sind keine Kirchen und Personen hinterlegt. Stellen Sie die Demo-Daten wieder her oder importieren Sie eine Sicherung.",
actionTitle: "Demo-Daten wiederherstellen",
action: { model.resetDemoData() }
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ScrollView(.horizontal, showsIndicators: false) {
VStack(spacing: 0) {
columnHeader(churchWidth: churchWidth)
Hairline()
if model.filteredRows.isEmpty {
EmptyStateView(
icon: "calendar",
title: "Keine Tage im Filter",
message: "Für diesen Zeitraum und Filter sind keine Einträge vorhanden."
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ScrollView(.vertical) {
LazyVStack(spacing: 0, pinnedViews: []) {
ForEach(monthGroups) { group in
monthHeader(group, churchWidth: churchWidth)
ForEach(group.rows) { row in
DayRow(
row: row,
churchWidth: churchWidth,
dateWidth: dateWidth,
liturgyWidth: liturgyWidth,
gap: gap,
horizontalPadding: horizontalPadding
)
}
}
}
.padding(.bottom, 10)
}
.padding(.bottom, 10)
}
}
.frame(width: width, height: geo.size.height, alignment: .top)
}
.frame(width: width, height: geo.size.height, alignment: .top)
}
}
}
@@ -510,6 +526,17 @@ private struct DayRow: View {
}
}
}
.overlay(alignment: .topTrailing) {
Button {
model.specialServiceEditor = SpecialServiceRequest(churchID: nil, date: row.date)
} label: {
Image(systemName: "plus.circle.fill")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(LP.burgundy.opacity(0.62))
}
.buttonStyle(.plain)
.help("Sondergottesdienst an diesem Tag hinzufügen")
}
}
private var liturgyCell: some View {
@@ -634,6 +661,12 @@ private struct ServiceCard: View {
.background(Capsule().fill(LP.openSoft))
}
}
if let location = service.service.location {
Text(location)
.font(.system(size: 7.5, weight: .medium))
.foregroundStyle(LP.burgundy)
.lineLimit(1)
}
ForEach(Role.allCases) { role in
if service.service.requiredCount(for: role) > 0 {
roleLine(role: role)
@@ -695,7 +728,7 @@ private struct ServiceCard: View {
private var helpText: String {
var lines = [
"\(service.church.name) · \(DayMath.longString(service.service.date)) · \(service.service.timeLabel)",
"\(service.service.placeName(church: service.church)) · \(DayMath.longString(service.service.date)) · \(service.service.timeLabel)",
service.service.title
]
for role in Role.allCases {
@@ -8,6 +8,7 @@ struct ServiceDetailSheet: View {
let serviceID: String
@State private var selectedRole: Role = .lector
@State private var ignorePreferredWeekdays = false
@State private var confirmDelete = false
private var item: ServiceWithAssignments? {
@@ -112,7 +113,7 @@ struct ServiceDetailSheet: View {
VStack(alignment: .leading, spacing: 3) {
HStack(spacing: 6) {
Text(item.church.name)
Text(item.service.placeName(church: item.church))
.font(.system(size: 10, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(churchColor)
@@ -148,6 +149,14 @@ struct ServiceDetailSheet: View {
.font(.system(size: 9, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
Toggle(isOn: $ignorePreferredWeekdays) {
Text("Präferenztage ignorieren")
.font(.system(size: 9, weight: .medium))
.foregroundStyle(LP.inkSecondary)
}
.toggleStyle(.switch)
.controlSize(.mini)
.help("Auch Personen anbieten, deren bevorzugte Einsatztage diesen Termin ausschließen. Ausschlusstermine bleiben gesperrt.")
}
}
.padding(.horizontal, 22)
@@ -342,7 +351,11 @@ struct ServiceDetailSheet: View {
Hairline()
let suggestions = model.candidateSuggestions(for: item.service, role: selectedRole)
let suggestions = model.candidateSuggestions(
for: item.service,
role: selectedRole,
ignorePreferredWeekdays: ignorePreferredWeekdays
)
if suggestions.isEmpty {
EmptyStateView(
icon: "person.crop.circle.badge.questionmark",
@@ -269,7 +269,10 @@ struct ServiceOrderView: View {
.font(.system(size: 11, weight: .medium))
.foregroundStyle(LP.ink)
}
Text([church?.name, service.notes].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))
let place = church.map { service.placeName(church: $0) } ?? service.location ?? ""
Text([place, service.notes]
.filter { !$0.isEmpty }
.joined(separator: " · "))
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.lineLimit(1)
+87 -14
View File
@@ -7,7 +7,39 @@ struct SettingsView: View {
@State private var autoSync = true
@State private var respectWeekdays = true
@State private var fairnessWeight = 2.2
@State private var confirmReset = false
@State private var dataAction: DataAction?
/// A single alert driver. Attaching two `.alert` modifiers to the same view
/// is unreliable on macOS, so both destructive actions share one alert.
private enum DataAction: String, Identifiable {
case resetDemo
case deleteAll
var id: String { rawValue }
var title: String {
switch self {
case .resetDemo: "Demo-Daten zurücksetzen?"
case .deleteAll: "Alle Daten löschen?"
}
}
var confirmTitle: String {
switch self {
case .resetDemo: "Zurücksetzen"
case .deleteAll: "Endgültig löschen"
}
}
var message: String {
switch self {
case .resetDemo:
"Sämtliche Kirchen, Personen, Vorlagen, Gottesdienste und Einsätze werden gelöscht und mit den Demo-Daten neu aufgebaut. Dieser Schritt kann nicht rückgängig gemacht werden."
case .deleteAll:
"Kirchen, Personen, Abwesenheiten, Vorlagen, Gottesdienste, Einsätze und liturgische Tage werden entfernt. Die App bleibt leer, bis Sie Demo-Daten zurücksetzen oder eine Sicherung importieren."
}
}
}
var body: some View {
VStack(spacing: 14) {
@@ -40,17 +72,24 @@ struct SettingsView: View {
.padding(.top, 30)
.padding(.bottom, 18)
.onAppear(perform: loadSettings)
.confirmationDialog(
"Demo-Daten zurücksetzen?",
isPresented: $confirmReset,
titleVisibility: .visible
) {
Button("Alle Daten zurücksetzen", role: .destructive) {
model.resetDemoData()
.alert(
dataAction?.title ?? "",
isPresented: Binding(
get: { dataAction != nil },
set: { if !$0 { dataAction = nil } }
),
presenting: dataAction
) { action in
Button("Abbrechen", role: .cancel) { dataAction = nil }
Button(action.confirmTitle, role: .destructive) {
switch action {
case .resetDemo: model.resetDemoData()
case .deleteAll: model.deleteAllData()
}
dataAction = nil
}
Button("Abbrechen", role: .cancel) {}
} message: {
Text("Sämtliche Kirchen, Personen, Vorlagen, Gottesdienste und Einsätze werden gelöscht und mit den Demo-Daten neu aufgebaut. Dieser Schritt kann nicht rückgängig gemacht werden.")
} message: { action in
Text(action.message)
}
}
@@ -193,7 +232,7 @@ struct SettingsView: View {
Image(systemName: "info.circle")
.font(.system(size: 10))
.foregroundStyle(LP.accent)
Text("Harte Ausschlüsse: Abwesenheit, fehlende Rolle, Monatslimit, Doppelbelegung am selben Tag. Gesperrte Einsätze werden bei einer Neuplanung nie verändert.")
Text("Harte Ausschlüsse: Abwesenheit, fehlende Rolle, Monatslimit, Doppelbelegung an verschiedenen Gottesdiensten am selben Tag. Lektor und Kommunionhelfer dürfen im selben Gottesdienst dieselbe Person sein. Gesperrte Einsätze werden bei einer Neuplanung nie verändert.")
.font(.system(size: 9))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
@@ -251,20 +290,51 @@ struct SettingsView: View {
model.exportInteractive(scope: .resources)
}
Spacer()
if model.isResettingData {
ProgressView()
.controlSize(.small)
Text("Datenbank wird neu aufgebaut…")
.font(.system(size: 10))
.foregroundStyle(LP.inkSecondary)
}
}
HStack(spacing: 9) {
Button {
confirmReset = true
dataAction = .resetDemo
} label: {
HStack(spacing: 5) {
Image(systemName: "arrow.counterclockwise")
Text("Demo-Daten zurücksetzen")
}
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.accent)
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.accent.opacity(0.08)))
}
.buttonStyle(.plain)
.disabled(model.isResettingData)
.help("Löscht alle Inhalte und baut den Demo-Bestand neu auf")
Button {
dataAction = .deleteAll
} label: {
HStack(spacing: 5) {
Image(systemName: "trash")
Text("Alle Daten löschen")
}
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.danger)
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(RoundedRectangle(cornerRadius: 7).fill(LP.danger.opacity(0.08)))
}
.buttonStyle(.plain)
.disabled(model.isResettingData)
.help("Entfernt alle Inhalte, ohne Demo-Daten neu anzulegen")
Spacer()
}
}
}
@@ -287,7 +357,10 @@ struct SettingsView: View {
Text("LektorenPlan")
.font(LP.serifHeadline)
.foregroundStyle(LP.ink)
Text("Prototyp 0.1 · Pfarreiengemeinschaft Bad Godesberg · Erzbistum Köln")
Text("Version \(AppMetadata.version) · Build \(AppMetadata.buildDateLabel)")
.font(.system(size: 9.5, weight: .medium))
.foregroundStyle(LP.inkSecondary)
Text("Pfarreiengemeinschaft Bad Godesberg · Erzbistum Köln")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
Text("Geplant werden Lektoren und Kommunionhelfer für St. Andreas, St. Evergislus, Herz Jesu und St. Hildegard. Liturgische Daten: www.eucharistiefeier.de (fair use). Alle Personen- und Plandaten in dieser Demo sind fiktiv.")
@@ -8,6 +8,7 @@ struct SpecialServiceSheet: View {
let request: SpecialServiceRequest
@State private var churchID = ""
@State private var location = ""
@State private var date = DayMath.today()
@State private var timeDate = Date()
@State private var title = ""
@@ -43,7 +44,7 @@ struct SpecialServiceSheet: View {
VStack(alignment: .leading, spacing: 22) {
FormSection(title: "Ort & Zeit") {
HStack(spacing: 12) {
LabeledField(label: "Kirche") {
LabeledField(label: "Kirche / Zuordnung") {
Picker("", selection: $churchID) {
ForEach(model.churches) { church in
Text(church.name).tag(church.id)
@@ -63,6 +64,13 @@ struct SpecialServiceSheet: View {
.datePickerStyle(.field)
}
}
LabeledField(label: "Ort (Freitext)") {
TextField("z. B. Open-Air auf dem Theaterplatz", text: $location)
.textFieldStyle(.roundedBorder)
}
Text("Leer lassen, wenn der Gottesdienst in der gewählten Kirche stattfindet. Der Freitext hat Vorrang vor dem Kirchnamen.")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
if let day = liturgicalDay {
@@ -154,6 +162,7 @@ struct SpecialServiceSheet: View {
existing = request.service
if let service = existing {
churchID = service.churchID
location = service.location ?? ""
date = service.date
timeDate = calendarTime(minutes: service.timeMinutes)
title = service.title
@@ -163,6 +172,7 @@ struct SpecialServiceSheet: View {
return
}
churchID = request.churchID ?? model.churches.first?.id ?? ""
location = ""
date = request.date
timeDate = calendarTime(minutes: 18 * 60)
if let day = liturgicalDay {
@@ -181,6 +191,7 @@ struct SpecialServiceSheet: View {
let service = ServiceOccurrence(
id: existing?.id ?? UUID().uuidString,
churchID: churchID,
location: location,
templateID: nil,
date: date,
timeMinutes: minutes,
+44 -11
View File
@@ -10,7 +10,11 @@ public final class AppDatabase {
self.path = path
self.database = try SQLiteDatabase(path: path)
try migrate()
if seedDemo, try churchCount() == 0 {
// Only seed on a genuinely fresh install. After the user explicitly
// deletes all data we persist a marker so demo data does not reappear.
if seedDemo,
try churchCount() == 0,
setting("suppressDemoSeed") != "1" {
try DemoData.seed(into: self)
}
}
@@ -91,6 +95,7 @@ public final class AppDatabase {
CREATE TABLE IF NOT EXISTS services (
id TEXT PRIMARY KEY,
church_id TEXT NOT NULL REFERENCES churches(id) ON DELETE CASCADE,
location TEXT NOT NULL DEFAULT '',
template_id TEXT REFERENCES service_templates(id) ON DELETE SET NULL,
date TEXT NOT NULL,
time_minutes INTEGER NOT NULL,
@@ -142,7 +147,19 @@ public final class AppDatabase {
);
"""
try database.execute(schema)
try database.run("INSERT OR IGNORE INTO settings(key, value) VALUES('schemaVersion', '1')")
// Older databases predate the free-text location for special services.
try addColumnIfMissing(
table: "services",
column: "location",
definition: "TEXT NOT NULL DEFAULT ''"
)
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('schemaVersion', '2')")
}
private func addColumnIfMissing(table: String, column: String, definition: String) throws {
let columns = try database.query("PRAGMA table_info(\(table))")
guard !columns.contains(where: { $0.string("name") == column }) else { return }
try database.execute("ALTER TABLE \(table) ADD COLUMN \(column) \(definition);")
}
// MARK: - Churches
@@ -375,15 +392,17 @@ public final class AppDatabase {
public func upsert(_ service: ServiceOccurrence) throws {
try database.run("""
INSERT INTO services(id, church_id, template_id, date, time_minutes, title, lectors_needed,
INSERT INTO services(id, church_id, location, template_id, date, time_minutes, title, lectors_needed,
helpers_needed, kind, notes, locked, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET church_id=excluded.church_id, template_id=excluded.template_id,
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET church_id=excluded.church_id, location=excluded.location,
template_id=excluded.template_id,
date=excluded.date, time_minutes=excluded.time_minutes, title=excluded.title,
lectors_needed=excluded.lectors_needed, helpers_needed=excluded.helpers_needed,
kind=excluded.kind, notes=excluded.notes, locked=excluded.locked
""", [
.text(service.id), .text(service.churchID), service.templateID.map(SQLiteValue.text) ?? .null,
.text(service.id), .text(service.churchID), .text(service.location ?? ""),
service.templateID.map(SQLiteValue.text) ?? .null,
.dateKey(service.date), .int(service.timeMinutes), .text(service.title),
.int(service.lectorsNeeded), .int(service.helpersNeeded), .text(service.kind.rawValue),
.text(service.notes), .bool(service.locked), .text(ISO8601DateFormatter().string(from: service.createdAt))
@@ -401,6 +420,7 @@ public final class AppDatabase {
return ServiceOccurrence(
id: id,
churchID: churchID,
location: row.string("location", default: ""),
templateID: row.string("template_id"),
date: date,
timeMinutes: row.int("time_minutes", default: 600),
@@ -739,12 +759,25 @@ public final class AppDatabase {
return value
}
/// Removes all content while keeping application settings (range, preferences).
/// By default a marker is stored so the demo dataset is not re-seeded on the
/// next launch; resetting the demo clears that marker again.
public func deleteAllData(markDemoSuppressed: Bool = true) throws {
try database.transaction {
try database.execute("""
DELETE FROM assignments; DELETE FROM services; DELETE FROM service_exceptions;
DELETE FROM service_templates; DELETE FROM absences; DELETE FROM people;
DELETE FROM churches; DELETE FROM liturgical_days;
""")
if markDemoSuppressed {
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('suppressDemoSeed', '1')")
}
}
}
public func resetDemoData() throws {
try database.execute("""
DELETE FROM assignments; DELETE FROM services; DELETE FROM service_exceptions;
DELETE FROM service_templates; DELETE FROM absences; DELETE FROM people;
DELETE FROM churches; DELETE FROM liturgical_days;
""")
try deleteAllData(markDemoSuppressed: false)
try database.run("DELETE FROM settings WHERE key='suppressDemoSeed'")
try DemoData.seed(into: self)
}
+5
View File
@@ -284,6 +284,11 @@ public enum DemoData {
ServiceOccurrence(churchID: Church.andreasID, date: date("2026-11-30"), timeMinutes: DayMath.minutes(hour: 18, minute: 0),
title: "Patronatsfest St. Andreas", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
notes: "Hochfest des heiligen Andreas"),
ServiceOccurrence(churchID: Church.herzJesuID, location: "Open-Air auf dem Theaterplatz",
date: date("2026-06-04"), timeMinutes: DayMath.minutes(hour: 10, minute: 0),
title: "Fronleichnamsmesse",
lectorsNeeded: 1, helpersNeeded: 2, kind: .special,
notes: "Gemeinsame Messfeier der Pfarreiengemeinschaft im Freien"),
ServiceOccurrence(churchID: Church.andreasID, date: date("2026-12-24"), timeMinutes: DayMath.minutes(hour: 16, minute: 0),
title: "Familienchristmette", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
notes: "Kinder- und Familienchristmette"),
+1 -1
View File
@@ -114,7 +114,7 @@ public struct LiturgicalCalendarAPI: Sendable {
var request = URLRequest(url: url)
request.timeoutInterval = 45
request.setValue("LektorenPlan/0.1 (macOS; Pfarrei Bad Godesberg)", forHTTPHeaderField: "User-Agent")
request.setValue("LektorenPlan/0.9 (macOS; Pfarrei Bad Godesberg)", forHTTPHeaderField: "User-Agent")
request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
let (data, response) = try await URLSession.shared.data(for: request)
+28
View File
@@ -35,6 +35,15 @@ public enum Role: String, Codable, CaseIterable, Identifiable, Sendable, Hashabl
case .helper: "hand.raised.fill"
}
}
/// The other role a service may need. Lector and communion helper do not
/// exclude each other, so one person can fill both at the same service.
public var complementary: Role {
switch self {
case .lector: .helper
case .helper: .lector
}
}
}
// MARK: - Church
@@ -155,6 +164,12 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
return "\(firstName) \(initial)."
}
/// Compact display for the calendar: surname in full, first name abbreviated.
public var abbreviatedName: String {
guard let initial = firstName.first else { return lastName }
return "\(initial). \(lastName)"
}
public var roleLabel: String {
let ordered = Role.allCases.filter { roles.contains($0) }
return ordered.map(\.title).joined(separator: " · ")
@@ -292,6 +307,9 @@ public enum ServiceKind: String, Codable, CaseIterable, Sendable {
public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var churchID: String
/// Free-text location for special services (e.g. open-air worship).
/// `nil` means the service takes place in the assigned church.
public var location: String?
public var templateID: String?
public var date: Date
public var timeMinutes: Int
@@ -306,6 +324,7 @@ public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
public init(
id: String = UUID().uuidString,
churchID: String,
location: String? = nil,
templateID: String? = nil,
date: Date,
timeMinutes: Int,
@@ -319,6 +338,8 @@ public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
) {
self.id = id
self.churchID = churchID
let trimmedLocation = location?.trimmingCharacters(in: .whitespacesAndNewlines)
self.location = (trimmedLocation?.isEmpty ?? true) ? nil : trimmedLocation
self.templateID = templateID
self.date = DayMath.normalize(date)
self.timeMinutes = timeMinutes
@@ -331,6 +352,10 @@ public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
self.createdAt = createdAt
}
public func placeName(church: Church) -> String {
location ?? church.name
}
public var timeLabel: String { DayMath.timeString(minutes: timeMinutes) }
public var dateKey: String { DayMath.key(date) }
public var requiredSlots: Int { lectorsNeeded + helpersNeeded }
@@ -877,6 +902,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
public var weightChurchPreference: Double
public var weightServicePreference: Double
public var weightFairness: Double
public var weightDualRolePreference: Double
public var maxAssignmentsPerDay: Int
public init(
@@ -886,6 +912,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
weightChurchPreference: Double = 8,
weightServicePreference: Double = 4,
weightFairness: Double = 2.2,
weightDualRolePreference: Double = 14,
maxAssignmentsPerDay: Int = 1
) {
self.replaceExisting = replaceExisting
@@ -894,6 +921,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
self.weightChurchPreference = weightChurchPreference
self.weightServicePreference = weightServicePreference
self.weightFairness = weightFairness
self.weightDualRolePreference = weightDualRolePreference
self.maxAssignmentsPerDay = maxAssignmentsPerDay
}
}
+51 -14
View File
@@ -39,7 +39,9 @@ public struct ServicePlanner {
var totalByPerson: [String: Int] = [:]
var monthByPerson: [String: Int] = [:]
var dayByPerson: [String: Int] = [:]
// Count distinct services per day. Both roles at the same service do not
// count as a double booking, so one person can be lector and helper there.
var dayServicesByPerson: [String: Set<String>] = [:]
var churchByPerson: [String: [String: Int]] = [:]
var lastDateByPerson: [String: Date] = [:]
@@ -48,7 +50,7 @@ public struct ServicePlanner {
let month = DayMath.monthKey(service.date)
totalByPerson[assignment.personID, default: 0] += 1
monthByPerson["\(assignment.personID)|\(month)", default: 0] += 1
dayByPerson["\(assignment.personID)|\(service.dateKey)", default: 0] += 1
dayServicesByPerson["\(assignment.personID)|\(service.dateKey)", default: []].insert(service.id)
churchByPerson[assignment.personID, default: [:]][service.churchID, default: 0] += 1
let previous = lastDateByPerson[assignment.personID]
if previous == nil || service.date > previous! {
@@ -66,6 +68,13 @@ public struct ServicePlanner {
var newAssignments: [Assignment] = []
for service in sortedServices {
// Roles already covered at this service. A person may appear in both
// roles, but not twice in the same role.
var assignedRolesByPerson: [String: Set<Role>] = [:]
for assignment in working where assignment.serviceID == service.id {
assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role)
}
for role in Role.allCases {
let required = service.requiredCount(for: role)
guard required > 0 else { continue }
@@ -73,7 +82,6 @@ public struct ServicePlanner {
if existingForRole >= required { continue }
for _ in existingForRole..<required {
let alreadyAssigned = Set(working.filter { $0.serviceID == service.id }.map(\.personID))
let result = bestCandidate(
for: service,
role: role,
@@ -82,10 +90,10 @@ public struct ServicePlanner {
absencesByPerson: absencesByPerson,
totalByPerson: totalByPerson,
monthByPerson: monthByPerson,
dayByPerson: dayByPerson,
dayServicesByPerson: dayServicesByPerson,
churchByPerson: churchByPerson,
lastDateByPerson: lastDateByPerson,
alreadyAssigned: alreadyAssigned
assignedRolesByPerson: assignedRolesByPerson
)
switch result {
case .success(let person):
@@ -98,9 +106,10 @@ public struct ServicePlanner {
working.append(assignment)
totalByPerson[person.id, default: 0] += 1
monthByPerson["\(person.id)|\(DayMath.monthKey(service.date))", default: 0] += 1
dayByPerson["\(person.id)|\(service.dateKey)", default: 0] += 1
dayServicesByPerson["\(person.id)|\(service.dateKey)", default: []].insert(service.id)
churchByPerson[person.id, default: [:]][service.churchID, default: 0] += 1
lastDateByPerson[person.id] = service.date
assignedRolesByPerson[person.id, default: []].insert(role)
case .failure(let reason):
unfilled.append(UnfilledSlot(
service: service,
@@ -144,17 +153,18 @@ public struct ServicePlanner {
absencesByPerson: [String: [Absence]],
totalByPerson: [String: Int],
monthByPerson: [String: Int],
dayByPerson: [String: Int],
dayServicesByPerson: [String: Set<String>],
churchByPerson: [String: [String: Int]],
lastDateByPerson: [String: Date],
alreadyAssigned: Set<String>
assignedRolesByPerson: [String: Set<Role>]
) -> CandidateResult {
var candidates: [(Person, Double)] = []
var blockedReasons: [String: Int] = [:]
var eligiblePeople: [Person] = []
for person in people where person.canFill(role) {
guard !alreadyAssigned.contains(person.id) else {
blockedReasons["bereits im Gottesdienst", default: 0] += 1
let assignedRoles = assignedRolesByPerson[person.id] ?? []
guard !assignedRoles.contains(role) else {
blockedReasons["bereits für diesen Dienst eingeteilt", default: 0] += 1
continue
}
if let absences = absencesByPerson[person.id], absences.contains(where: { $0.overlaps(service.date) }) {
@@ -173,13 +183,41 @@ public struct ServicePlanner {
blockedReasons["Monatslimit erreicht", default: 0] += 1
continue
}
let usedThisDay = dayByPerson["\(person.id)|\(service.dateKey)", default: 0]
if usedThisDay >= options.maxAssignmentsPerDay {
let usedServicesThisDay = dayServicesByPerson["\(person.id)|\(service.dateKey)", default: []]
// A second role at the very same service is not a double booking.
if usedServicesThisDay.count >= options.maxAssignmentsPerDay,
!usedServicesThisDay.isSubset(of: [service.id]) {
blockedReasons["bereits an diesem Tag", default: 0] += 1
continue
}
eligiblePeople.append(person)
}
// The dual-role preference is a tie-breaker, not a way to concentrate
// assignments on one person. If another suitable person has noticeably
// fewer assignments, fairness takes priority over giving both roles to
// the same person.
let minimumTotal = eligiblePeople.map { totalByPerson[$0.id, default: 0] }.min() ?? 0
let fairnessSlack = 1
var candidates: [(Person, Double)] = []
for person in eligiblePeople {
let assignedRoles = assignedRolesByPerson[person.id] ?? []
let total = totalByPerson[person.id, default: 0]
let withinFairnessReach = total - minimumTotal <= fairnessSlack
var score = 10.0
if withinFairnessReach, assignedRoles.contains(role.complementary) {
// The same person already covers the other role here — prefer
// keeping both duties with them while the distribution stays fair.
score += options.weightDualRolePreference
} else if withinFairnessReach,
service.rolesNeeded.count > 1,
person.roles.contains(where: { $0 != role && service.requiredCount(for: $0) > 0 }) {
// On services needing both roles, favour people who can cover both.
score += options.weightDualRolePreference
}
if person.preferredChurchIDs.contains(service.churchID) {
score += options.weightChurchPreference
}
@@ -197,7 +235,6 @@ public struct ServicePlanner {
if person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
score += 3
}
let total = totalByPerson[person.id, default: 0]
score -= Double(total) * options.weightFairness
let churchCount = churchByPerson[person.id]?[service.churchID, default: 0] ?? 0
score -= Double(churchCount) * 0.4