1. Prototyp
This commit is contained in:
1 parent
e723eee440
commit
c24bc91768
37 files changed
+11610
No files matched your search
@@ -0,0 +1,236 @@
|
||||
import Foundation
|
||||
|
||||
public struct ServicePlanner {
|
||||
public var people: [Person]
|
||||
public var absences: [Absence]
|
||||
public var services: [ServiceOccurrence]
|
||||
public var existingAssignments: [Assignment]
|
||||
public var churches: [Church]
|
||||
public var options: PlannerOptions
|
||||
|
||||
public init(
|
||||
people: [Person],
|
||||
absences: [Absence],
|
||||
services: [ServiceOccurrence],
|
||||
existingAssignments: [Assignment] = [],
|
||||
churches: [Church] = [],
|
||||
options: PlannerOptions = PlannerOptions()
|
||||
) {
|
||||
self.people = people
|
||||
self.absences = absences
|
||||
self.services = services
|
||||
self.existingAssignments = existingAssignments
|
||||
self.churches = churches
|
||||
self.options = options
|
||||
}
|
||||
|
||||
public func plan() -> PlanResult {
|
||||
let activePeople = people.filter(\.active)
|
||||
let peopleByID = Dictionary(uniqueKeysWithValues: activePeople.map { ($0.id, $0) })
|
||||
let absencesByPerson = Dictionary(grouping: absences, by: \.personID)
|
||||
let churchNames = Dictionary(uniqueKeysWithValues: churches.map { ($0.id, $0.name) })
|
||||
|
||||
var working: [Assignment]
|
||||
if options.replaceExisting {
|
||||
working = existingAssignments.filter(\.locked)
|
||||
} else {
|
||||
working = existingAssignments
|
||||
}
|
||||
|
||||
var totalByPerson: [String: Int] = [:]
|
||||
var monthByPerson: [String: Int] = [:]
|
||||
var dayByPerson: [String: Int] = [:]
|
||||
var churchByPerson: [String: [String: Int]] = [:]
|
||||
var lastDateByPerson: [String: Date] = [:]
|
||||
|
||||
for assignment in working {
|
||||
guard let service = services.first(where: { $0.id == assignment.serviceID }) else { continue }
|
||||
let month = DayMath.monthKey(service.date)
|
||||
totalByPerson[assignment.personID, default: 0] += 1
|
||||
monthByPerson["\(assignment.personID)|\(month)", default: 0] += 1
|
||||
dayByPerson["\(assignment.personID)|\(service.dateKey)", default: 0] += 1
|
||||
churchByPerson[assignment.personID, default: [:]][service.churchID, default: 0] += 1
|
||||
let previous = lastDateByPerson[assignment.personID]
|
||||
if previous == nil || service.date > previous! {
|
||||
lastDateByPerson[assignment.personID] = service.date
|
||||
}
|
||||
}
|
||||
|
||||
let sortedServices = services.sorted {
|
||||
if $0.date != $1.date { return $0.date < $1.date }
|
||||
if $0.timeMinutes != $1.timeMinutes { return $0.timeMinutes < $1.timeMinutes }
|
||||
return $0.id < $1.id
|
||||
}
|
||||
|
||||
var unfilled: [UnfilledSlot] = []
|
||||
var newAssignments: [Assignment] = []
|
||||
|
||||
for service in sortedServices {
|
||||
for role in Role.allCases {
|
||||
let required = service.requiredCount(for: role)
|
||||
guard required > 0 else { continue }
|
||||
let existingForRole = working.filter { $0.serviceID == service.id && $0.role == role }.count
|
||||
if existingForRole >= required { continue }
|
||||
|
||||
for _ in existingForRole..<required {
|
||||
let alreadyAssigned = Set(working.filter { $0.serviceID == service.id }.map(\.personID))
|
||||
let result = bestCandidate(
|
||||
for: service,
|
||||
role: role,
|
||||
people: activePeople,
|
||||
peopleByID: peopleByID,
|
||||
absencesByPerson: absencesByPerson,
|
||||
totalByPerson: totalByPerson,
|
||||
monthByPerson: monthByPerson,
|
||||
dayByPerson: dayByPerson,
|
||||
churchByPerson: churchByPerson,
|
||||
lastDateByPerson: lastDateByPerson,
|
||||
alreadyAssigned: alreadyAssigned
|
||||
)
|
||||
switch result {
|
||||
case .success(let person):
|
||||
let assignment = Assignment(
|
||||
serviceID: service.id,
|
||||
personID: person.id,
|
||||
role: role
|
||||
)
|
||||
newAssignments.append(assignment)
|
||||
working.append(assignment)
|
||||
totalByPerson[person.id, default: 0] += 1
|
||||
monthByPerson["\(person.id)|\(DayMath.monthKey(service.date))", default: 0] += 1
|
||||
dayByPerson["\(person.id)|\(service.dateKey)", default: 0] += 1
|
||||
churchByPerson[person.id, default: [:]][service.churchID, default: 0] += 1
|
||||
lastDateByPerson[person.id] = service.date
|
||||
case .failure(let reason):
|
||||
unfilled.append(UnfilledSlot(
|
||||
service: service,
|
||||
churchName: churchNames[service.churchID] ?? "",
|
||||
role: role,
|
||||
reason: reason
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let filled = newAssignments.count
|
||||
let message: String
|
||||
if filled == 0 && unfilled.isEmpty {
|
||||
message = "Alle Dienste im Zeitraum sind bereits vollständig besetzt."
|
||||
} else if unfilled.isEmpty {
|
||||
message = "\(filled) Dienst\(filled == 1 ? "" : "e") erfolgreich besetzt. Alle Lücken geschlossen."
|
||||
} else {
|
||||
message = "\(filled) Dienst\(filled == 1 ? "" : "e") besetzt, \(unfilled.count) Lücke\(unfilled.count == 1 ? "" : "n") bleiben offen."
|
||||
}
|
||||
|
||||
if options.replaceExisting {
|
||||
let locked = working.filter(\.locked)
|
||||
let combined = locked + newAssignments
|
||||
return PlanResult(assignments: combined, unfilled: unfilled, filledCount: filled, message: message)
|
||||
}
|
||||
return PlanResult(assignments: working, unfilled: unfilled, filledCount: filled, message: message)
|
||||
}
|
||||
|
||||
private enum CandidateResult {
|
||||
case success(Person)
|
||||
case failure(String)
|
||||
}
|
||||
|
||||
private func bestCandidate(
|
||||
for service: ServiceOccurrence,
|
||||
role: Role,
|
||||
people: [Person],
|
||||
peopleByID: [String: Person],
|
||||
absencesByPerson: [String: [Absence]],
|
||||
totalByPerson: [String: Int],
|
||||
monthByPerson: [String: Int],
|
||||
dayByPerson: [String: Int],
|
||||
churchByPerson: [String: [String: Int]],
|
||||
lastDateByPerson: [String: Date],
|
||||
alreadyAssigned: Set<String>
|
||||
) -> CandidateResult {
|
||||
var candidates: [(Person, Double)] = []
|
||||
var blockedReasons: [String: Int] = [:]
|
||||
|
||||
for person in people where person.canFill(role) {
|
||||
guard !alreadyAssigned.contains(person.id) else {
|
||||
blockedReasons["bereits im Gottesdienst", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
if let absences = absencesByPerson[person.id], absences.contains(where: { $0.overlaps(service.date) }) {
|
||||
blockedReasons["abwesend", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
if options.respectPreferredWeekdays,
|
||||
!person.preferredWeekdays.isEmpty,
|
||||
!person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
|
||||
blockedReasons["Einsatztag passt nicht", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
let month = DayMath.monthKey(service.date)
|
||||
let usedThisMonth = monthByPerson["\(person.id)|\(month)", default: 0]
|
||||
if person.maxPerMonth > 0, usedThisMonth >= person.maxPerMonth {
|
||||
blockedReasons["Monatslimit erreicht", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
let usedThisDay = dayByPerson["\(person.id)|\(service.dateKey)", default: 0]
|
||||
if usedThisDay >= options.maxAssignmentsPerDay {
|
||||
blockedReasons["bereits an diesem Tag", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
|
||||
var score = 10.0
|
||||
if person.preferredChurchIDs.contains(service.churchID) {
|
||||
score += options.weightChurchPreference
|
||||
}
|
||||
if !person.preferredChurchIDs.isEmpty && !person.preferredChurchIDs.contains(service.churchID) {
|
||||
score -= 1.5
|
||||
}
|
||||
if !person.preferredServiceTitles.isEmpty {
|
||||
let title = service.title.lowercased()
|
||||
for preference in person.preferredServiceTitles where !preference.isEmpty {
|
||||
if title.contains(preference.lowercased()) {
|
||||
score += options.weightServicePreference
|
||||
}
|
||||
}
|
||||
}
|
||||
if person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
|
||||
score += 3
|
||||
}
|
||||
let total = totalByPerson[person.id, default: 0]
|
||||
score -= Double(total) * options.weightFairness
|
||||
let churchCount = churchByPerson[person.id]?[service.churchID, default: 0] ?? 0
|
||||
score -= Double(churchCount) * 0.4
|
||||
if let last = lastDateByPerson[person.id] {
|
||||
let gap = DayMath.daysBetween(last, service.date)
|
||||
if gap >= 14 { score += 1.8 } else if gap >= 7 { score += 0.8 }
|
||||
} else {
|
||||
score += 2.5
|
||||
}
|
||||
score += stableTieBreak("\(person.id)|\(service.id)|\(role.rawValue)")
|
||||
|
||||
candidates.append((person, score))
|
||||
}
|
||||
|
||||
guard let best = candidates.max(by: { $0.1 < $1.1 }) else {
|
||||
let reason: String
|
||||
if blockedReasons.isEmpty {
|
||||
reason = "Keine geeignete Person mit Rolle \(role.title)"
|
||||
} else if let top = blockedReasons.max(by: { $0.value < $1.value }) {
|
||||
reason = "\(top.key) (\(top.value) ausgeschlossen)"
|
||||
} else {
|
||||
reason = "Keine geeignete Person"
|
||||
}
|
||||
return .failure(reason)
|
||||
}
|
||||
return .success(best.0)
|
||||
}
|
||||
|
||||
private func stableTieBreak(_ value: String) -> Double {
|
||||
var hash = 5381
|
||||
for byte in value.utf8 {
|
||||
hash = ((hash << 5) &+ hash) &+ Int(byte)
|
||||
}
|
||||
return Double(abs(hash % 997)) / 100_000
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user