import Foundation public struct ServicePlanner { public var people: [Person] public var absences: [Absence] public var services: [ServiceOccurrence] public var existingAssignments: [Assignment] public var churches: [Church] public var options: PlannerOptions public init( people: [Person], absences: [Absence], services: [ServiceOccurrence], existingAssignments: [Assignment] = [], churches: [Church] = [], options: PlannerOptions = PlannerOptions() ) { self.people = people self.absences = absences self.services = services self.existingAssignments = existingAssignments self.churches = churches self.options = options } public func plan() -> PlanResult { let activePeople = people.filter(\.active) let peopleByID = Dictionary(uniqueKeysWithValues: activePeople.map { ($0.id, $0) }) let absencesByPerson = Dictionary(grouping: absences, by: \.personID) let churchNames = Dictionary(uniqueKeysWithValues: churches.map { ($0.id, $0.name) }) var working: [Assignment] if options.replaceExisting { working = existingAssignments.filter(\.locked) } else { working = existingAssignments } var totalByPerson: [String: Int] = [:] var monthByPerson: [String: Int] = [:] // 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] = [:] 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] = [:] 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..], churchByPerson: [String: [String: Int]], lastDateByPerson: [String: Date], assignedRolesByPerson: [String: Set] ) -> 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, !person.preferredWeekdays.isEmpty, !person.preferredWeekdays.contains(DayMath.weekday(service.date)) { blockedReasons["Einsatztag passt nicht", default: 0] += 1 continue } let month = DayMath.monthKey(service.date) let usedThisMonth = monthByPerson["\(person.id)|\(month)", default: 0] if person.maxPerMonth > 0, usedThisMonth >= person.maxPerMonth { blockedReasons["Monatslimit erreicht", default: 0] += 1 continue } let 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.preferredWeekdays.contains(DayMath.weekday(service.date)) { 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 } }