Gastansicht, Verbesserungen bei Planung

This commit is contained in:
concierge committed 2026-11-18 07:57:00 +01:00
1 parent b3afa3ef32
commit c08d43e7dd
38 files changed
+3845 -219

No files matched your search

+57 -11
View File
@@ -68,6 +68,7 @@ enum PlanFilter: String, CaseIterable, Identifiable {
case all
case services
case open
case beyond
var id: String { rawValue }
@@ -76,6 +77,7 @@ enum PlanFilter: String, CaseIterable, Identifiable {
case .all: "Alle Tage"
case .services: "Mit Gottesdiensten"
case .open: "Nur offene"
case .beyond: "Über Präferenzen"
}
}
}
@@ -144,6 +146,7 @@ struct CandidateSuggestion: Identifiable {
var warnings: [String]
var blocked: Bool
var preferred: Bool
var beyondPreferences: Bool
var totalAssignments: Int
var id: String { person.id }
@@ -347,6 +350,8 @@ final class PlanModel: ObservableObject {
if !row.hasServices { return false }
case .open:
if row.openSlots == 0 { return false }
case .beyond:
if !row.hasBeyondPreferences { return false }
}
guard !query.isEmpty else { return true }
if row.liturgicalDay?.title.lowercased().contains(query) == true { return true }
@@ -382,7 +387,7 @@ final class PlanModel: ObservableObject {
// MARK: - Planning
func autoPlan(replaceExisting: Bool) -> PlanResult? {
func autoPlan(replaceExisting: Bool, allowBeyond: Bool = false) -> PlanResult? {
guard !isPlanning else { return nil }
isPlanning = true
defer { isPlanning = false }
@@ -390,8 +395,11 @@ final class PlanModel: ObservableObject {
let rangeServices = try db.services(in: range)
let existing = try db.assignments(in: range)
let options = PlannerOptions(
replaceExisting: replaceExisting,
// A follow-up pass keeps the result of the first pass and only
// adds assignments for volunteers who allowed them.
replaceExisting: allowBeyond ? false : replaceExisting,
respectPreferredWeekdays: db.setting("respectPreferredWeekdays") != "0",
allowBeyondPreferences: allowBeyond,
weightFairness: Double(db.setting("fairnessWeight") ?? "") ?? 2.2,
maxAssignmentsPerDay: 1
)
@@ -401,11 +409,12 @@ final class PlanModel: ObservableObject {
services: rangeServices,
existingAssignments: existing,
churches: churches,
liturgicalDays: Array(liturgicalDays.values),
options: options
)
let result = planner.plan()
if result.filledCount > 0 || replaceExisting {
try db.savePlan(result.assignments, in: range, replaceUnlocked: replaceExisting)
try db.savePlan(result.assignments, in: range, replaceUnlocked: allowBeyond ? false : replaceExisting)
}
loadAll()
planResult = result
@@ -429,6 +438,7 @@ final class PlanModel: ObservableObject {
services: [service],
existingAssignments: existing.filter { $0.serviceID == serviceID },
churches: churches,
liturgicalDays: Array(liturgicalDays.values),
options: PlannerOptions(replaceExisting: false, respectPreferredWeekdays: false)
)
let result = planner.plan()
@@ -448,7 +458,27 @@ final class PlanModel: ObservableObject {
func assign(serviceID: String, role: Role, personID: String?) {
do {
try db.setAssignment(serviceID: serviceID, role: role, personID: personID)
var beyond = false
if let personID, let person = peopleByID[personID], let service = try db.service(id: serviceID) {
let highFeast = liturgicalDays[service.dateKey]?.isHighFeast ?? false
let fits = person.matchesWeekdayPreference(
weekday: DayMath.weekday(service.date),
timeMinutes: service.timeMinutes,
highFeast: highFeast
)
beyond = !fits
if !beyond, person.maxPerMonth > 0 {
let monthAssignments = try db.assignments(in: DayRange.month(containing: service.date))
let used = monthAssignments.filter {
$0.personID == personID && $0.serviceID != serviceID
}.count
beyond = used >= person.maxPerMonth
}
}
try db.setAssignment(
serviceID: serviceID, role: role, personID: personID,
beyondPreferences: beyond
)
loadAll()
if let personID, let person = peopleByID[personID] {
showToast("\(person.fullName) als \(role.title) eingetragen.", kind: .success)
@@ -501,6 +531,7 @@ final class PlanModel: ObservableObject {
assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role)
}
let weekday = DayMath.weekday(service.date)
let highFeast = liturgicalDays[service.dateKey]?.isHighFeast ?? false
let eligiblePeople = people.filter { person in
guard person.active, person.canFill(role) else { return false }
@@ -515,19 +546,33 @@ final class PlanModel: ObservableObject {
.map { person in
var warnings: [String] = []
var blocked = false
var beyond = false
if absences.contains(where: { $0.personID == person.id && $0.overlaps(service.date) }) {
warnings.append("abwesend")
blocked = true
}
if !ignorePreferredWeekdays,
!person.preferredWeekdays.isEmpty,
!person.preferredWeekdays.contains(weekday) {
warnings.append("Einsatztag passt nicht")
blocked = true
let weekdayMatch = person.matchesWeekdayPreference(
weekday: weekday,
timeMinutes: service.timeMinutes,
highFeast: highFeast
)
if !weekdayMatch {
if ignorePreferredWeekdays {
beyond = true
} else if person.allowBeyondPreferences {
beyond = true
} else {
warnings.append("Einsatztag oder Uhrzeit passt nicht")
blocked = true
}
}
if person.maxPerMonth > 0, monthlyCounts["\(person.id)|\(monthKey)", default: 0] >= person.maxPerMonth {
warnings.append("Monatslimit")
blocked = true
if person.allowBeyondPreferences {
beyond = true
} else {
blocked = true
}
}
let servicesThisDay = dayServices["\(person.id)|\(service.dateKey)", default: []]
if !servicesThisDay.isEmpty, !servicesThisDay.isSubset(of: [service.id]) {
@@ -554,7 +599,7 @@ final class PlanModel: ObservableObject {
if !person.preferredChurchIDs.isEmpty && !person.preferredChurchIDs.contains(service.churchID) {
score -= 2
}
if person.preferredWeekdays.contains(weekday) {
if weekdayMatch, !person.preferredWeekdays.isEmpty {
score += 3
preferred = true
}
@@ -574,6 +619,7 @@ final class PlanModel: ObservableObject {
warnings: warnings,
blocked: blocked,
preferred: preferred,
beyondPreferences: beyond,
totalAssignments: totalCounts[person.id, default: 0]
)
}
+22 -4
View File
@@ -270,24 +270,42 @@ struct PersonMiniChip: View {
var person: Person
var role: Role
var color: Color
var beyond: Bool = false
var body: some View {
HStack(spacing: 4) {
Avatar(initials: person.initials, color: color, size: 18)
if beyond {
Image(systemName: "arrow.up.right")
.font(.system(size: 7, weight: .black))
.foregroundStyle(LP.burgundy)
}
Text(person.abbreviatedName)
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
.foregroundStyle(beyond ? LP.burgundy : LP.ink)
.lineLimit(1)
}
.padding(.horizontal, 4)
.padding(.vertical, 2)
.background(
Capsule().fill(LP.cardMuted)
Capsule().fill(beyond ? LP.burgundySoft.opacity(0.7) : LP.cardMuted)
)
.overlay(
Capsule().strokeBorder(LP.line.opacity(0.5), lineWidth: 0.6)
Capsule().strokeBorder(
beyond ? LP.burgundy.opacity(0.5) : LP.line.opacity(0.5),
style: StrokeStyle(lineWidth: 0.6, dash: beyond ? [2, 1.5] : [])
)
)
.help("\(person.fullName) · \(role.title)\n\(person.preferredChurchIDs.isEmpty ? "Alle Orte" : "Bevorzugte Orte") · max. \(person.maxPerMonth) Einsätze/Monat")
.help(chipHelp)
}
private var chipHelp: String {
var lines = ["\(person.fullName) · \(role.title)"]
lines.append(person.preferredChurchIDs.isEmpty ? "Alle Orte" : "Bevorzugte Orte")
lines.append("max. \(person.maxPerMonth) Einsätze/Monat")
if beyond { lines.append("Über die Präferenzen hinaus eingeplant") }
if !person.preferenceNote.isEmpty { lines.append(person.preferenceNote) }
return lines.joined(separator: "\n")
}
}
@@ -9,13 +9,16 @@ struct PersonEditorSheet: View {
@State private var firstName = ""
@State private var lastName = ""
@State private var shortCode = ""
@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 weekdayPeriods: [Int: WeekdayPeriod] = [:]
@State private var preferredServiceTitles: Set<String> = []
@State private var maxPerMonth = 6
@State private var allowBeyondPreferences = false
@State private var active = true
@State private var notes = ""
@@ -33,6 +36,13 @@ struct PersonEditorSheet: View {
["", "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"][max(0, min(7, weekday))]
}
private func periodBinding(_ weekday: Int) -> Binding<WeekdayPeriod> {
Binding(
get: { weekdayPeriods[weekday] ?? .all },
set: { weekdayPeriods[weekday] = $0 }
)
}
private var isValid: Bool {
!firstName.trimmingCharacters(in: .whitespaces).isEmpty
&& !lastName.trimmingCharacters(in: .whitespaces).isEmpty
@@ -118,7 +128,15 @@ struct PersonEditorSheet: View {
TextField("z. B. Berg", text: $lastName)
.textFieldStyle(.roundedBorder)
}
LabeledField(label: "Kürzel") {
TextField("optional", text: $shortCode)
.textFieldStyle(.roundedBorder)
.frame(width: 90)
}
}
Text("Das Kürzel erscheint in der Gastansicht. Ohne Kürzel werden die Initialen angezeigt.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
HStack(spacing: 12) {
LabeledField(label: "E-Mail") {
TextField("optional", text: $email)
@@ -195,21 +213,39 @@ struct PersonEditorSheet: View {
Text("Bevorzugte Einsatztage")
.font(.system(size: 9.5, weight: .semibold))
.foregroundStyle(LP.inkSecondary)
HStack(spacing: 5) {
HStack(alignment: .top, spacing: 5) {
ForEach(weekdayOrder, id: \.self) { weekday in
ChipToggle(
title: weekdayLabel(weekday),
isOn: preferredWeekdays.contains(weekday),
tint: weekday == 1 ? LP.burgundy : LP.accent
) {
VStack(spacing: 3) {
ChipToggle(
title: weekdayLabel(weekday),
isOn: preferredWeekdays.contains(weekday),
tint: weekday == 1 ? LP.burgundy : LP.accent
) {
if preferredWeekdays.contains(weekday) {
preferredWeekdays.remove(weekday)
weekdayPeriods[weekday] = nil
} else {
preferredWeekdays.insert(weekday)
weekdayPeriods[weekday] = .all
}
}
if preferredWeekdays.contains(weekday) {
preferredWeekdays.remove(weekday)
} else {
preferredWeekdays.insert(weekday)
Picker("Tageszeit", selection: periodBinding(weekday)) {
ForEach(WeekdayPeriod.allCases) { period in
Text(period.shortLabel).tag(period)
}
}
.labelsHidden()
.pickerStyle(.menu)
.controlSize(.mini)
.frame(width: 88)
}
}
}
}
Text("Hochfeste gelten zusätzlich als Sonntag. Die Tageszeit grenzt den Einsatztag ein (vormittags 0–12, nachmittags 12–17, abends ab 17 Uhr).")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
}
VStack(alignment: .leading, spacing: 5) {
@@ -262,6 +298,21 @@ struct PersonEditorSheet: View {
.background(RoundedRectangle(cornerRadius: 7).fill(LP.card))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.8), lineWidth: 1))
}
Text("Diese Notiz erscheint in der Dienstplanung bei Einsätzen und Vorschlägen.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
Toggle(isOn: $allowBeyondPreferences) {
VStack(alignment: .leading, spacing: 1) {
Text("Auch über Präferenzen hinaus planbar")
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.inkSecondary)
Text("Die Person kann nach Rückfrage für Dienste außerhalb ihrer Tage, Zeiten und ihres Monatslimits eingeplant werden.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
}
}
.toggleStyle(.switch)
.controlSize(.small)
}
}
@@ -350,13 +401,16 @@ struct PersonEditorSheet: View {
}
firstName = person.firstName
lastName = person.lastName
shortCode = person.shortCode
email = person.email
phone = person.phone
roles = person.roles
preferredChurchIDs = person.preferredChurchIDs
preferredWeekdays = person.preferredWeekdays
weekdayPeriods = Dictionary(uniqueKeysWithValues: person.preferredWeekdayPeriods.map { ($0.weekday, $0.period) })
preferredServiceTitles = Set(person.preferredServiceTitles)
maxPerMonth = person.maxPerMonth
allowBeyondPreferences = person.allowBeyondPreferences
active = person.active
notes = person.notes
}
@@ -378,6 +432,7 @@ struct PersonEditorSheet: View {
private func save() {
let person = Person(
id: personID ?? UUID().uuidString,
shortCode: shortCode.trimmingCharacters(in: .whitespaces),
firstName: firstName.trimmingCharacters(in: .whitespaces),
lastName: lastName.trimmingCharacters(in: .whitespaces),
roles: roles,
@@ -385,8 +440,12 @@ struct PersonEditorSheet: View {
phone: phone.trimmingCharacters(in: .whitespaces),
preferredChurchIDs: preferredChurchIDs,
preferredWeekdays: preferredWeekdays,
preferredWeekdayPeriods: preferredWeekdays.sorted().map {
WeekdayPeriodPreference(weekday: $0, period: weekdayPeriods[$0] ?? .all)
},
preferredServiceTitles: Array(preferredServiceTitles).sorted(),
maxPerMonth: maxPerMonth,
allowBeyondPreferences: allowBeyondPreferences,
active: active,
notes: notes.trimmingCharacters(in: .whitespacesAndNewlines)
)
@@ -8,6 +8,9 @@ struct PlanResultSheet: View {
var body: some View {
VStack(spacing: 0) {
if let result = model.planResult {
let canOfferBeyond = !result.unfilled.isEmpty
&& !result.assignments.contains(where: \.beyondPreferences)
&& model.people.contains { $0.active && $0.allowBeyondPreferences }
SheetHeader(
icon: result.unfilled.isEmpty ? "checkmark.seal" : "exclamationmark.triangle",
title: result.unfilled.isEmpty ? "Planung abgeschlossen" : "Planung mit Lücken",
@@ -98,12 +101,31 @@ struct PlanResultSheet: View {
.clipShape(RoundedRectangle(cornerRadius: 9))
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(LP.line.opacity(0.55), lineWidth: 0.8))
}
if canOfferBeyond {
let flagged = model.people.filter { $0.active && $0.allowBeyondPreferences }
HStack(alignment: .top, spacing: 9) {
Image(systemName: "arrow.up.right.circle")
.foregroundStyle(LP.burgundy)
Text("\(flagged.count) \(flagged.count == 1 ? "Person hat" : "Personen haben") sich bereit erklärt, nach Rückfrage auch über die eigenen Präferenzen hinaus eingeplant zu werden. Diese Einsätze werden im Plan besonders gekennzeichnet.")
.font(.system(size: 10.5))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
.padding(12)
.background(RoundedRectangle(cornerRadius: 10).fill(LP.burgundySoft.opacity(0.5)))
}
}
}
.padding(22)
}
SheetFooter {
if canOfferBeyond {
PrimaryActionButton(title: "Über Präferenzen hinaus planen", icon: "arrow.up.right") {
_ = model.autoPlan(replaceExisting: false, allowBeyond: true)
}
}
Spacer()
SecondaryActionButton(title: "Statistik ansehen", icon: "chart.xyaxis.line") {
model.planResult = nil
+61 -15
View File
@@ -158,6 +158,7 @@ private struct CalendarTable: View {
private let horizontalPadding: CGFloat = 12
private let dateWidth: CGFloat = 86
private let liturgyWidth: CGFloat = 240
private let actionWidth: CGFloat = 22
private let churchMinWidth: CGFloat = 186
var body: some View {
@@ -166,9 +167,9 @@ private struct CalendarTable: View {
toolbar
Hairline()
GeometryReader { geo in
let minimum = horizontalPadding * 2 + dateWidth + liturgyWidth + churchMinWidth * 4 + gap * 5
let minimum = horizontalPadding * 2 + dateWidth + liturgyWidth + actionWidth + churchMinWidth * 4 + gap * 6
let width = max(geo.size.width, minimum)
let churchWidth = (width - horizontalPadding * 2 - dateWidth - liturgyWidth - gap * 5) / 4
let churchWidth = (width - horizontalPadding * 2 - dateWidth - liturgyWidth - actionWidth - gap * 6) / 4
if model.churches.isEmpty {
EmptyStateView(
icon: "building.columns",
@@ -201,6 +202,7 @@ private struct CalendarTable: View {
churchWidth: churchWidth,
dateWidth: dateWidth,
liturgyWidth: liturgyWidth,
actionWidth: actionWidth,
gap: gap,
horizontalPadding: horizontalPadding
)
@@ -317,6 +319,14 @@ private struct CalendarTable: View {
}
.font(.system(size: 8.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
HStack(spacing: 3) {
Image(systemName: "arrow.up.right")
.font(.system(size: 8, weight: .bold))
.foregroundStyle(LP.burgundy)
Text("über Präferenzen")
}
.font(.system(size: 8.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
}
}
@@ -345,6 +355,8 @@ private struct CalendarTable: View {
ForEach(model.churches) { church in
ChurchColumnHeader(church: church, width: churchWidth)
}
Text("")
.frame(width: actionWidth)
}
.padding(.horizontal, horizontalPadding)
.padding(.vertical, 10)
@@ -369,7 +381,7 @@ private struct CalendarTable: View {
}
.padding(.horizontal, horizontalPadding)
.padding(.vertical, 7)
.frame(width: horizontalPadding * 2 + dateWidth + liturgyWidth + churchWidth * 4 + gap * 5, alignment: .leading)
.frame(width: horizontalPadding * 2 + dateWidth + liturgyWidth + actionWidth + churchWidth * 4 + gap * 6, alignment: .leading)
.background(LP.paperDeep.opacity(0.55))
.overlay(alignment: .top) { Hairline() }
.overlay(alignment: .bottom) { Hairline().opacity(0.55) }
@@ -440,6 +452,7 @@ private struct DayRow: View {
var churchWidth: CGFloat
var dateWidth: CGFloat
var liturgyWidth: CGFloat
var actionWidth: CGFloat
var gap: CGFloat
var horizontalPadding: CGFloat
@@ -459,6 +472,16 @@ private struct DayRow: View {
churchCell(church: church)
.frame(width: churchWidth, alignment: .topLeading)
}
Button {
model.specialServiceEditor = SpecialServiceRequest(churchID: nil, date: row.date)
} label: {
Image(systemName: "plus.circle.fill")
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(LP.burgundy.opacity(0.6))
}
.buttonStyle(.plain)
.help("Sondergottesdienst an diesem Tag hinzufügen")
.frame(width: actionWidth, alignment: .trailing)
}
.padding(.horizontal, horizontalPadding)
.padding(.vertical, 9)
@@ -526,17 +549,6 @@ 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 {
@@ -624,6 +636,7 @@ private struct ServiceCard: View {
@EnvironmentObject private var model: PlanModel
var service: ServiceWithAssignments
var liturgy: LiturgicalDay?
@State private var confirmDelete = false
private var churchColor: Color { LP.churchColor(service.church.colorHex) }
@@ -674,6 +687,7 @@ private struct ServiceCard: View {
}
}
.padding(.horizontal, 7)
.padding(.trailing, 10)
.padding(.vertical, 6)
.frame(maxWidth: .infinity, alignment: .leading)
.background(
@@ -693,6 +707,30 @@ private struct ServiceCard: View {
}
.buttonStyle(.plain)
.help(helpText)
.overlay(alignment: .bottomTrailing) {
Button {
confirmDelete = true
} label: {
Image(systemName: "trash")
.font(.system(size: 8, weight: .semibold))
.foregroundStyle(LP.danger.opacity(0.65))
.padding(3)
}
.buttonStyle(.plain)
.help("Gottesdienst löschen")
}
.confirmationDialog(
"Gottesdienst löschen?",
isPresented: $confirmDelete,
titleVisibility: .visible
) {
Button("Endgültig löschen", role: .destructive) {
model.deleteService(service.service)
}
Button("Abbrechen", role: .cancel) {}
} message: {
Text("Der Termin und alle zugehörigen Einsätze werden entfernt. Die Gottesdienstordnung bleibt unverändert.")
}
}
private func roleLine(role: Role) -> some View {
@@ -713,7 +751,12 @@ private struct ServiceCard: View {
} else {
ForEach(assigned) { assignment in
if let person = model.peopleByID[assignment.personID] {
PersonMiniChip(person: person, role: role, color: churchColor)
PersonMiniChip(
person: person,
role: role,
color: churchColor,
beyond: assignment.beyondPreferences
)
}
}
if open > 0 {
@@ -742,6 +785,9 @@ private struct ServiceCard: View {
if !liturgy.remark.isEmpty { lines.append(liturgy.remark) }
}
if !service.service.notes.isEmpty { lines.append(service.service.notes) }
if service.assignments.contains(where: \.beyondPreferences) {
lines.append("Mindestens ein Einsatz geht über die Präferenzen hinaus")
}
lines.append("Klicken zum Bearbeiten")
return lines.joined(separator: "\n")
}
@@ -45,17 +45,18 @@ struct ServiceDetailSheet: View {
.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")
}
Button {
confirmDelete = true
} label: {
Image(systemName: "trash")
.font(.system(size: 11.5, weight: .medium))
.foregroundStyle(LP.danger)
}
.buttonStyle(.plain)
.help("Gottesdienst löschen")
Spacer()
SecondaryActionButton(title: "Schließen", icon: "xmark") { dismiss() }
PrimaryActionButton(title: "Automatisch besetzen", icon: "wand.and.stars") {
@@ -79,11 +80,11 @@ struct ServiceDetailSheet: View {
}
}
.confirmationDialog(
"Sondergottesdienst löschen?",
"Gottesdienst löschen?",
isPresented: $confirmDelete,
titleVisibility: .visible
) {
Button("Löschen", role: .destructive) {
Button("Endgültig löschen", role: .destructive) {
if let item {
model.deleteService(item.service)
}
@@ -91,7 +92,7 @@ struct ServiceDetailSheet: View {
}
Button("Abbrechen", role: .cancel) {}
} message: {
Text("Der Termin und alle zugehörigen Einsätze werden entfernt.")
Text("Der Termin und alle zugehörigen Einsätze werden entfernt. Die Gottesdienstordnung bleibt unverändert.")
}
}
@@ -286,12 +287,24 @@ struct ServiceDetailSheet: View {
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)
HStack(spacing: 5) {
Text(person.fullName)
.font(.system(size: 11, weight: .medium))
.foregroundStyle(LP.ink)
if assignment.beyondPreferences {
TinyBadge(text: "ÜBER PRÄFERENZEN", color: LP.burgundy)
}
}
Text(person.roleLabel)
.font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary)
if !person.preferenceNote.isEmpty {
Text(person.preferenceNote)
.font(.system(size: 8.5))
.italic()
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
}
Spacer()
Button {
@@ -400,6 +413,16 @@ struct ServiceDetailSheet: View {
if candidate.person.roles.contains(.lector) && candidate.person.roles.contains(.helper) {
TinyBadge(text: "L+K", color: LP.accent)
}
if candidate.beyondPreferences {
TinyBadge(text: "ÜBER PRÄFERENZEN", color: LP.burgundy)
}
}
if !candidate.person.preferenceNote.isEmpty {
Text(candidate.person.preferenceNote)
.font(.system(size: 8.5))
.italic()
.foregroundStyle(LP.inkSecondary)
.lineLimit(2)
}
HStack(spacing: 6) {
Text("\(candidate.totalAssignments) Einsätze im Zeitraum")
+58 -15
View File
@@ -47,6 +47,7 @@ public final class AppDatabase {
CREATE TABLE IF NOT EXISTS people (
id TEXT PRIMARY KEY,
short_code TEXT NOT NULL DEFAULT '',
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
roles TEXT NOT NULL,
@@ -54,8 +55,10 @@ public final class AppDatabase {
phone TEXT NOT NULL DEFAULT '',
preferred_church_ids TEXT NOT NULL DEFAULT '[]',
preferred_weekdays TEXT NOT NULL DEFAULT '[]',
preferred_weekday_periods TEXT NOT NULL DEFAULT '[]',
preferred_service_titles TEXT NOT NULL DEFAULT '[]',
max_per_month INTEGER NOT NULL DEFAULT 6,
allow_beyond_preferences INTEGER NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 1,
notes TEXT NOT NULL DEFAULT ''
);
@@ -118,6 +121,7 @@ public final class AppDatabase {
person_id TEXT NOT NULL REFERENCES people(id) ON DELETE CASCADE,
role TEXT NOT NULL,
locked INTEGER NOT NULL DEFAULT 0,
beyond_preferences INTEGER NOT NULL DEFAULT 0,
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
UNIQUE(service_id, person_id, role)
@@ -178,7 +182,14 @@ public final class AppDatabase {
column: "location",
definition: "TEXT NOT NULL DEFAULT ''"
)
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('schemaVersion', '3')")
// People gained a Kürzel, weekday time periods and permission to be
// planned beyond their preferences.
try addColumnIfMissing(table: "people", column: "short_code", definition: "TEXT NOT NULL DEFAULT ''")
try addColumnIfMissing(table: "people", column: "preferred_weekday_periods", definition: "TEXT NOT NULL DEFAULT '[]'")
try addColumnIfMissing(table: "people", column: "allow_beyond_preferences", definition: "INTEGER NOT NULL DEFAULT 0")
// Assignments record when a volunteer was planned beyond preferences.
try addColumnIfMissing(table: "assignments", column: "beyond_preferences", definition: "INTEGER NOT NULL DEFAULT 0")
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('schemaVersion', '4')")
}
private func addColumnIfMissing(table: String, column: String, definition: String) throws {
@@ -246,22 +257,30 @@ public final class AppDatabase {
let roles = encode(person.roles.map(\.rawValue).sorted())
let churches = encode(person.preferredChurchIDs.sorted())
let weekdays = encode(person.preferredWeekdays.sorted())
let periods = encode(person.preferredWeekdayPeriods.sorted { $0.weekday < $1.weekday })
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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
INSERT INTO people(id, short_code, first_name, last_name, roles, email, phone, preferred_church_ids,
preferred_weekdays, preferred_weekday_periods, preferred_service_titles,
max_per_month, allow_beyond_preferences, active, notes)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
short_code=excluded.short_code,
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_weekday_periods=excluded.preferred_weekday_periods,
preferred_service_titles=excluded.preferred_service_titles,
max_per_month=excluded.max_per_month, active=excluded.active, notes=excluded.notes
max_per_month=excluded.max_per_month,
allow_beyond_preferences=excluded.allow_beyond_preferences,
active=excluded.active, notes=excluded.notes
""", [
.text(person.id), .text(person.firstName), .text(person.lastName), .text(roles),
.text(person.id), .text(person.shortCode.trimmingCharacters(in: .whitespacesAndNewlines)),
.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)
.text(periods), .text(titles), .int(person.maxPerMonth),
.bool(person.allowBeyondPreferences), .bool(person.active), .text(person.notes)
])
}
@@ -277,6 +296,7 @@ public final class AppDatabase {
let roleStrings: [String] = decode(row.string("roles", default: "[]"))
return Person(
id: id,
shortCode: row.string("short_code", default: ""),
firstName: first,
lastName: last,
roles: Set(roleStrings.compactMap(Role.init(rawValue:))),
@@ -284,8 +304,10 @@ public final class AppDatabase {
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]),
preferredWeekdayPeriods: decode(row.string("preferred_weekday_periods", default: "[]")),
preferredServiceTitles: decode(row.string("preferred_service_titles", default: "[]")),
maxPerMonth: row.int("max_per_month", default: 6),
allowBeyondPreferences: row.bool("allow_beyond_preferences", default: false),
active: row.bool("active", default: true),
notes: row.string("notes", default: "")
)
@@ -545,29 +567,49 @@ public final class AppDatabase {
public func upsert(_ assignment: Assignment) throws {
try database.run("""
INSERT INTO assignments(id, service_id, person_id, role, locked, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?)
INSERT INTO assignments(id, service_id, person_id, role, locked, beyond_preferences, 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
role=excluded.role, locked=excluded.locked,
beyond_preferences=excluded.beyond_preferences, note=excluded.note
""", [
.text(assignment.id), .text(assignment.serviceID), .text(assignment.personID),
.text(assignment.role.rawValue), .bool(assignment.locked), .text(assignment.note),
.text(assignment.role.rawValue), .bool(assignment.locked),
.bool(assignment.beyondPreferences), .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 {
public func setAssignment(
serviceID: String,
role: Role,
personID: String?,
locked: Bool = false,
beyondPreferences: 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)
let assignment = Assignment(
serviceID: serviceID, personID: personID, role: role,
locked: locked, beyondPreferences: beyondPreferences
)
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 setAssignment(
serviceID: String,
personID: String?,
role: Role,
locked: Bool = false,
beyondPreferences: Bool = false
) throws {
try setAssignment(
serviceID: serviceID, role: role, personID: personID,
locked: locked, beyondPreferences: beyondPreferences
)
}
public func deleteAssignment(id: String) throws {
@@ -605,6 +647,7 @@ public final class AppDatabase {
personID: personID,
role: role,
locked: row.bool("locked", default: false),
beyondPreferences: row.bool("beyond_preferences", default: false),
note: row.string("note", default: ""),
createdAt: ISO8601DateFormatter().date(from: row.string("created_at", default: "")) ?? Date()
)
+164
View File
@@ -107,8 +107,58 @@ public struct Church: Identifiable, Codable, Hashable, Sendable {
// MARK: - People
public enum WeekdayPeriod: String, Codable, CaseIterable, Identifiable, Sendable, Hashable {
case all
case morning
case afternoon
case evening
public var id: String { rawValue }
public var label: String {
switch self {
case .morning: "vormittags (0–12 Uhr)"
case .afternoon: "nachmittags (12–17 Uhr)"
case .evening: "abends (ab 17 Uhr)"
case .all: "ganztägig"
}
}
public var shortLabel: String {
switch self {
case .morning: "vormittags"
case .afternoon: "nachmittags"
case .evening: "abends"
case .all: "ganztägig"
}
}
/// Morning is 0–12, afternoon 12–17, evening after 17.
public func matches(timeMinutes: Int) -> Bool {
switch self {
case .morning: timeMinutes < 12 * 60
case .afternoon: timeMinutes >= 12 * 60 && timeMinutes < 17 * 60
case .evening: timeMinutes >= 17 * 60
case .all: true
}
}
}
public struct WeekdayPeriodPreference: Codable, Hashable, Sendable, Identifiable {
public var weekday: Int
public var period: WeekdayPeriod
public var id: Int { weekday }
public init(weekday: Int, period: WeekdayPeriod = .all) {
self.weekday = weekday
self.period = period
}
}
public struct Person: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var shortCode: String
public var firstName: String
public var lastName: String
public var roles: Set<Role>
@@ -116,13 +166,16 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
public var phone: String
public var preferredChurchIDs: Set<String>
public var preferredWeekdays: Set<Int> // 1 = Sunday … 7 = Saturday; empty = no preference
public var preferredWeekdayPeriods: [WeekdayPeriodPreference]
public var preferredServiceTitles: [String]
public var maxPerMonth: Int
public var allowBeyondPreferences: Bool
public var active: Bool
public var notes: String
public init(
id: String = UUID().uuidString,
shortCode: String = "",
firstName: String,
lastName: String,
roles: Set<Role> = [.lector],
@@ -130,12 +183,15 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
phone: String = "",
preferredChurchIDs: Set<String> = [],
preferredWeekdays: Set<Int> = [],
preferredWeekdayPeriods: [WeekdayPeriodPreference] = [],
preferredServiceTitles: [String] = [],
maxPerMonth: Int = 6,
allowBeyondPreferences: Bool = false,
active: Bool = true,
notes: String = ""
) {
self.id = id
self.shortCode = shortCode
self.firstName = firstName
self.lastName = lastName
self.roles = roles
@@ -143,12 +199,42 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
self.phone = phone
self.preferredChurchIDs = preferredChurchIDs
self.preferredWeekdays = preferredWeekdays
self.preferredWeekdayPeriods = preferredWeekdayPeriods
self.preferredServiceTitles = preferredServiceTitles
self.maxPerMonth = maxPerMonth
self.allowBeyondPreferences = allowBeyondPreferences
self.active = active
self.notes = notes
}
private enum CodingKeys: String, CodingKey {
case id, shortCode, firstName, lastName, roles, email, phone
case preferredChurchIDs, preferredWeekdays, preferredWeekdayPeriods
case preferredServiceTitles, maxPerMonth, allowBeyondPreferences
case active, notes
}
/// Older exchange files and backups predate the Kürzel, weekday periods and
/// the beyond-preferences flag, so every new key falls back to a default.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? UUID().uuidString
shortCode = try container.decodeIfPresent(String.self, forKey: .shortCode) ?? ""
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
roles = try container.decodeIfPresent(Set<Role>.self, forKey: .roles) ?? [.lector]
email = try container.decodeIfPresent(String.self, forKey: .email) ?? ""
phone = try container.decodeIfPresent(String.self, forKey: .phone) ?? ""
preferredChurchIDs = try container.decodeIfPresent(Set<String>.self, forKey: .preferredChurchIDs) ?? []
preferredWeekdays = try container.decodeIfPresent(Set<Int>.self, forKey: .preferredWeekdays) ?? []
preferredWeekdayPeriods = try container.decodeIfPresent([WeekdayPeriodPreference].self, forKey: .preferredWeekdayPeriods) ?? []
preferredServiceTitles = try container.decodeIfPresent([String].self, forKey: .preferredServiceTitles) ?? []
maxPerMonth = try container.decodeIfPresent(Int.self, forKey: .maxPerMonth) ?? 6
allowBeyondPreferences = try container.decodeIfPresent(Bool.self, forKey: .allowBeyondPreferences) ?? false
active = try container.decodeIfPresent(Bool.self, forKey: .active) ?? true
notes = try container.decodeIfPresent(String.self, forKey: .notes) ?? ""
}
public var fullName: String {
"\(firstName) \(lastName)".trimmingCharacters(in: .whitespaces)
}
@@ -176,6 +262,34 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
}
public func canFill(_ role: Role) -> Bool { roles.contains(role) }
/// Guest-facing label: an explicitly maintained Kürzel wins, otherwise the
/// initials from first and last name.
public var displayShort: String {
let code = shortCode.trimmingCharacters(in: .whitespacesAndNewlines)
return code.isEmpty ? initials : code
}
public func weekdayPeriod(for weekday: Int) -> WeekdayPeriod {
preferredWeekdayPeriods.first { $0.weekday == weekday }?.period ?? .all
}
/// High feasts count like Sundays, so a Sunday preference also covers them.
/// An empty weekday list means no restriction.
public func matchesWeekdayPreference(weekday: Int, timeMinutes: Int, highFeast: Bool) -> Bool {
guard !preferredWeekdays.isEmpty else { return true }
var candidates = [weekday]
if highFeast && weekday != 1 { candidates.append(1) }
for day in candidates where preferredWeekdays.contains(day) {
if weekdayPeriod(for: day).matches(timeMinutes: timeMinutes) { return true }
}
return false
}
/// Free-text planning note shown next to assignments and candidates.
public var preferenceNote: String {
notes.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
public struct Absence: Identifiable, Codable, Hashable, Sendable {
@@ -380,6 +494,7 @@ public struct Assignment: Identifiable, Codable, Hashable, Sendable {
public var personID: String
public var role: Role
public var locked: Bool
public var beyondPreferences: Bool
public var note: String
public var createdAt: Date
@@ -389,6 +504,7 @@ public struct Assignment: Identifiable, Codable, Hashable, Sendable {
personID: String,
role: Role,
locked: Bool = false,
beyondPreferences: Bool = false,
note: String = "",
createdAt: Date = Date()
) {
@@ -397,9 +513,28 @@ public struct Assignment: Identifiable, Codable, Hashable, Sendable {
self.personID = personID
self.role = role
self.locked = locked
self.beyondPreferences = beyondPreferences
self.note = note
self.createdAt = createdAt
}
private enum CodingKeys: String, CodingKey {
case id, serviceID, personID, role, locked, beyondPreferences, note, createdAt
}
/// Exchange files created before the beyond-preferences marker decode to
/// the ordinary case.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? UUID().uuidString
serviceID = try container.decode(String.self, forKey: .serviceID)
personID = try container.decode(String.self, forKey: .personID)
role = try container.decode(Role.self, forKey: .role)
locked = try container.decodeIfPresent(Bool.self, forKey: .locked) ?? false
beyondPreferences = try container.decodeIfPresent(Bool.self, forKey: .beyondPreferences) ?? false
note = try container.decodeIfPresent(String.self, forKey: .note) ?? ""
createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? Date()
}
}
// MARK: - Liturgy
@@ -710,6 +845,13 @@ public struct DayPlanRow: Identifiable, Hashable, Sendable {
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 }
/// Marks days with at least one assignment beyond the person's preferences.
public var hasBeyondPreferences: Bool {
services.contains { service in
service.assignments.contains(where: \.beyondPreferences)
}
}
}
public struct UnfilledSlot: Identifiable, Hashable, Sendable {
@@ -898,6 +1040,7 @@ public struct ExchangeSummary: Hashable, Sendable {
public struct PlannerOptions: Codable, Hashable, Sendable {
public var replaceExisting: Bool
public var respectPreferredWeekdays: Bool
public var allowBeyondPreferences: Bool
public var allowDoubleRolesOnSameDay: Bool
public var weightChurchPreference: Double
public var weightServicePreference: Double
@@ -908,6 +1051,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
public init(
replaceExisting: Bool = false,
respectPreferredWeekdays: Bool = true,
allowBeyondPreferences: Bool = false,
allowDoubleRolesOnSameDay: Bool = false,
weightChurchPreference: Double = 8,
weightServicePreference: Double = 4,
@@ -917,6 +1061,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
) {
self.replaceExisting = replaceExisting
self.respectPreferredWeekdays = respectPreferredWeekdays
self.allowBeyondPreferences = allowBeyondPreferences
self.allowDoubleRolesOnSameDay = allowDoubleRolesOnSameDay
self.weightChurchPreference = weightChurchPreference
self.weightServicePreference = weightServicePreference
@@ -924,6 +1069,25 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
self.weightDualRolePreference = weightDualRolePreference
self.maxAssignmentsPerDay = maxAssignmentsPerDay
}
private enum CodingKeys: String, CodingKey {
case replaceExisting, respectPreferredWeekdays, allowBeyondPreferences
case allowDoubleRolesOnSameDay, weightChurchPreference, weightServicePreference
case weightFairness, weightDualRolePreference, maxAssignmentsPerDay
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
replaceExisting = try container.decodeIfPresent(Bool.self, forKey: .replaceExisting) ?? false
respectPreferredWeekdays = try container.decodeIfPresent(Bool.self, forKey: .respectPreferredWeekdays) ?? true
allowBeyondPreferences = try container.decodeIfPresent(Bool.self, forKey: .allowBeyondPreferences) ?? false
allowDoubleRolesOnSameDay = try container.decodeIfPresent(Bool.self, forKey: .allowDoubleRolesOnSameDay) ?? false
weightChurchPreference = try container.decodeIfPresent(Double.self, forKey: .weightChurchPreference) ?? 8
weightServicePreference = try container.decodeIfPresent(Double.self, forKey: .weightServicePreference) ?? 4
weightFairness = try container.decodeIfPresent(Double.self, forKey: .weightFairness) ?? 2.2
weightDualRolePreference = try container.decodeIfPresent(Double.self, forKey: .weightDualRolePreference) ?? 14
maxAssignmentsPerDay = try container.decodeIfPresent(Int.self, forKey: .maxAssignmentsPerDay) ?? 1
}
}
public struct PlanResult: Sendable {
+75 -8
View File
@@ -6,6 +6,7 @@ public struct ServicePlanner {
public var services: [ServiceOccurrence]
public var existingAssignments: [Assignment]
public var churches: [Church]
public var liturgicalDays: [LiturgicalDay]
public var options: PlannerOptions
public init(
@@ -14,6 +15,7 @@ public struct ServicePlanner {
services: [ServiceOccurrence],
existingAssignments: [Assignment] = [],
churches: [Church] = [],
liturgicalDays: [LiturgicalDay] = [],
options: PlannerOptions = PlannerOptions()
) {
self.people = people
@@ -21,6 +23,7 @@ public struct ServicePlanner {
self.services = services
self.existingAssignments = existingAssignments
self.churches = churches
self.liturgicalDays = liturgicalDays
self.options = options
}
@@ -29,6 +32,7 @@ public struct ServicePlanner {
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) })
let highFeastDates = Set(liturgicalDays.filter(\.isHighFeast).map(\.dateKey))
var working: [Assignment]
if options.replaceExisting {
@@ -93,7 +97,9 @@ public struct ServicePlanner {
dayServicesByPerson: dayServicesByPerson,
churchByPerson: churchByPerson,
lastDateByPerson: lastDateByPerson,
assignedRolesByPerson: assignedRolesByPerson
assignedRolesByPerson: assignedRolesByPerson,
highFeast: highFeastDates.contains(service.dateKey),
enforcePreferences: true
)
switch result {
case .success(let person):
@@ -122,6 +128,58 @@ public struct ServicePlanner {
}
}
// Second pass, only on explicit request: use volunteers who agreed to be
// planned beyond their preferences for the slots that remained open.
if options.allowBeyondPreferences, !unfilled.isEmpty {
let flagged = activePeople.filter(\.allowBeyondPreferences)
if !flagged.isEmpty {
var remaining: [UnfilledSlot] = []
for slot in unfilled {
let service = slot.service
var assignedRolesByPerson: [String: Set<Role>] = [:]
for assignment in working where assignment.serviceID == service.id {
assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role)
}
let result = bestCandidate(
for: service,
role: slot.role,
people: flagged,
peopleByID: peopleByID,
absencesByPerson: absencesByPerson,
totalByPerson: totalByPerson,
monthByPerson: monthByPerson,
dayServicesByPerson: dayServicesByPerson,
churchByPerson: churchByPerson,
lastDateByPerson: lastDateByPerson,
assignedRolesByPerson: assignedRolesByPerson,
highFeast: highFeastDates.contains(service.dateKey),
enforcePreferences: false
)
switch result {
case .success(let person):
let assignment = Assignment(
serviceID: service.id,
personID: person.id,
role: slot.role,
beyondPreferences: true
)
newAssignments.append(assignment)
working.append(assignment)
totalByPerson[person.id, default: 0] += 1
monthByPerson["\(person.id)|\(DayMath.monthKey(service.date))", 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
case .failure(let reason):
var updated = slot
updated.reason = reason
remaining.append(updated)
}
}
unfilled = remaining
}
}
let filled = newAssignments.count
let message: String
if filled == 0 && unfilled.isEmpty {
@@ -156,7 +214,9 @@ public struct ServicePlanner {
dayServicesByPerson: [String: Set<String>],
churchByPerson: [String: [String: Int]],
lastDateByPerson: [String: Date],
assignedRolesByPerson: [String: Set<Role>]
assignedRolesByPerson: [String: Set<Role>],
highFeast: Bool,
enforcePreferences: Bool
) -> CandidateResult {
var blockedReasons: [String: Int] = [:]
var eligiblePeople: [Person] = []
@@ -171,15 +231,18 @@ public struct ServicePlanner {
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
if options.respectPreferredWeekdays, enforcePreferences,
!person.matchesWeekdayPreference(
weekday: DayMath.weekday(service.date),
timeMinutes: service.timeMinutes,
highFeast: highFeast
) {
blockedReasons["Einsatztag oder Uhrzeit 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 {
if enforcePreferences, person.maxPerMonth > 0, usedThisMonth >= person.maxPerMonth {
blockedReasons["Monatslimit erreicht", default: 0] += 1
continue
}
@@ -232,7 +295,11 @@ public struct ServicePlanner {
}
}
}
if person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
if person.matchesWeekdayPreference(
weekday: DayMath.weekday(service.date),
timeMinutes: service.timeMinutes,
highFeast: highFeast
), !person.preferredWeekdays.isEmpty {
score += 3
}
score -= Double(total) * options.weightFairness