Files
LektorenPlan/Sources/LektorenPlanCore/Planner.swift
T

341 lines
16 KiB
Swift

import Foundation
public struct ServicePlanner {
public var people: [Person]
public var absences: [Absence]
public var services: [ServiceOccurrence]
public var existingAssignments: [Assignment]
public var churches: [Church]
public var liturgicalDays: [LiturgicalDay]
public var options: PlannerOptions
public init(
people: [Person],
absences: [Absence],
services: [ServiceOccurrence],
existingAssignments: [Assignment] = [],
churches: [Church] = [],
liturgicalDays: [LiturgicalDay] = [],
options: PlannerOptions = PlannerOptions()
) {
self.people = people
self.absences = absences
self.services = services
self.existingAssignments = existingAssignments
self.churches = churches
self.liturgicalDays = liturgicalDays
self.options = options
}
public func plan() -> PlanResult {
let activePeople = people.filter(\.active)
let peopleByID = Dictionary(uniqueKeysWithValues: activePeople.map { ($0.id, $0) })
let absencesByPerson = Dictionary(grouping: absences, by: \.personID)
let churchNames = Dictionary(uniqueKeysWithValues: churches.map { ($0.id, $0.name) })
let highFeastDates = Set(liturgicalDays.filter(\.isHighFeast).map(\.dateKey))
var working: [Assignment]
if options.replaceExisting {
working = existingAssignments.filter(\.locked)
} else {
working = existingAssignments
}
var totalByPerson: [String: Int] = [:]
var monthByPerson: [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] = [:]
for assignment in working {
guard let service = services.first(where: { $0.id == assignment.serviceID }) else { continue }
let month = DayMath.monthKey(service.date)
totalByPerson[assignment.personID, default: 0] += 1
monthByPerson["\(assignment.personID)|\(month)", default: 0] += 1
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! {
lastDateByPerson[assignment.personID] = service.date
}
}
let sortedServices = services.sorted {
if $0.date != $1.date { return $0.date < $1.date }
if $0.timeMinutes != $1.timeMinutes { return $0.timeMinutes < $1.timeMinutes }
return $0.id < $1.id
}
var unfilled: [UnfilledSlot] = []
var newAssignments: [Assignment] = []
for service in sortedServices {
// 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 }
let existingForRole = working.filter { $0.serviceID == service.id && $0.role == role }.count
if existingForRole >= required { continue }
for _ in existingForRole..<required {
let result = bestCandidate(
for: service,
role: role,
people: activePeople,
peopleByID: peopleByID,
absencesByPerson: absencesByPerson,
totalByPerson: totalByPerson,
monthByPerson: monthByPerson,
dayServicesByPerson: dayServicesByPerson,
churchByPerson: churchByPerson,
lastDateByPerson: lastDateByPerson,
assignedRolesByPerson: assignedRolesByPerson,
highFeast: highFeastDates.contains(service.dateKey),
enforcePreferences: true
)
switch result {
case .success(let person):
let assignment = Assignment(
serviceID: service.id,
personID: person.id,
role: role
)
newAssignments.append(assignment)
working.append(assignment)
totalByPerson[person.id, default: 0] += 1
monthByPerson["\(person.id)|\(DayMath.monthKey(service.date))", default: 0] += 1
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,
churchName: churchNames[service.churchID] ?? "",
role: role,
reason: reason
))
}
}
}
}
// 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 {
message = "Alle Dienste im Zeitraum sind bereits vollständig besetzt."
} else if unfilled.isEmpty {
message = "\(filled) Dienst\(filled == 1 ? "" : "e") erfolgreich besetzt. Alle Lücken geschlossen."
} else {
message = "\(filled) Dienst\(filled == 1 ? "" : "e") besetzt, \(unfilled.count) Lücke\(unfilled.count == 1 ? "" : "n") bleiben offen."
}
if options.replaceExisting {
let locked = working.filter(\.locked)
let combined = locked + newAssignments
return PlanResult(assignments: combined, unfilled: unfilled, filledCount: filled, message: message)
}
return PlanResult(assignments: working, unfilled: unfilled, filledCount: filled, message: message)
}
private enum CandidateResult {
case success(Person)
case failure(String)
}
private func bestCandidate(
for service: ServiceOccurrence,
role: Role,
people: [Person],
peopleByID: [String: Person],
absencesByPerson: [String: [Absence]],
totalByPerson: [String: Int],
monthByPerson: [String: Int],
dayServicesByPerson: [String: Set<String>],
churchByPerson: [String: [String: Int]],
lastDateByPerson: [String: Date],
assignedRolesByPerson: [String: Set<Role>],
highFeast: Bool,
enforcePreferences: Bool
) -> CandidateResult {
var blockedReasons: [String: Int] = [:]
var eligiblePeople: [Person] = []
for person in people where person.canFill(role) {
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) }) {
blockedReasons["abwesend", default: 0] += 1
continue
}
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 enforcePreferences, person.maxPerMonth > 0, usedThisMonth >= person.maxPerMonth {
blockedReasons["Monatslimit erreicht", default: 0] += 1
continue
}
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
}
if !person.preferredChurchIDs.isEmpty && !person.preferredChurchIDs.contains(service.churchID) {
score -= 1.5
}
if !person.preferredServiceTitles.isEmpty {
let title = service.title.lowercased()
for preference in person.preferredServiceTitles where !preference.isEmpty {
if title.contains(preference.lowercased()) {
score += options.weightServicePreference
}
}
}
if person.matchesWeekdayPreference(
weekday: DayMath.weekday(service.date),
timeMinutes: service.timeMinutes,
highFeast: highFeast
), !person.preferredWeekdays.isEmpty {
score += 3
}
score -= Double(total) * options.weightFairness
let churchCount = churchByPerson[person.id]?[service.churchID, default: 0] ?? 0
score -= Double(churchCount) * 0.4
if let last = lastDateByPerson[person.id] {
let gap = DayMath.daysBetween(last, service.date)
if gap >= 14 { score += 1.8 } else if gap >= 7 { score += 0.8 }
} else {
score += 2.5
}
score += stableTieBreak("\(person.id)|\(service.id)|\(role.rawValue)")
candidates.append((person, score))
}
guard let best = candidates.max(by: { $0.1 < $1.1 }) else {
let reason: String
if blockedReasons.isEmpty {
reason = "Keine geeignete Person mit Rolle \(role.title)"
} else if let top = blockedReasons.max(by: { $0.value < $1.value }) {
reason = "\(top.key) (\(top.value) ausgeschlossen)"
} else {
reason = "Keine geeignete Person"
}
return .failure(reason)
}
return .success(best.0)
}
private func stableTieBreak(_ value: String) -> Double {
var hash = 5381
for byte in value.utf8 {
hash = ((hash << 5) &+ hash) &+ Int(byte)
}
return Double(abs(hash % 997)) / 100_000
}
}