package domain import ( "fmt" "sort" "strings" "time" ) // ServicePlanner implements the automatic assignment rules of the macOS app. type ServicePlanner struct { People []Person Absences []Absence Services []ServiceOccurrence ExistingAssignments []Assignment Churches []Church LiturgicalDays []LiturgicalDay Options PlannerOptions } type candidateResult struct { person *Person reason string } func (p ServicePlanner) Plan() PlanResult { activePeople := make([]Person, 0, len(p.People)) for _, person := range p.People { if person.Active { activePeople = append(activePeople, person) } } absencesByPerson := map[string][]Absence{} for _, a := range p.Absences { absencesByPerson[a.PersonID] = append(absencesByPerson[a.PersonID], a) } churchNames := map[string]string{} for _, c := range p.Churches { churchNames[c.ID] = c.Name } serviceByID := map[string]ServiceOccurrence{} for _, s := range p.Services { serviceByID[s.ID] = s } highFeastByDate := map[string]bool{} for _, day := range p.LiturgicalDays { if day.IsHighFeast() { highFeastByDate[day.DateKey()] = true } } working := make([]Assignment, 0, len(p.ExistingAssignments)) for _, a := range p.ExistingAssignments { if !p.Options.ReplaceExisting || a.Locked { working = append(working, a) } } totalByPerson := map[string]int{} monthByPerson := map[string]int{} dayServicesByPerson := map[string]map[string]bool{} churchByPerson := map[string]map[string]int{} lastDateByPerson := map[string]time.Time{} roleCounts := map[string]map[Role]int{} rolesByServicePerson := map[string]map[string]map[Role]bool{} applyToCounts := func(a Assignment, s ServiceOccurrence) { totalByPerson[a.PersonID]++ monthByPerson[a.PersonID+"|"+MonthKey(s.Date)]++ key := a.PersonID + "|" + s.DateKey() if dayServicesByPerson[key] == nil { dayServicesByPerson[key] = map[string]bool{} } dayServicesByPerson[key][s.ID] = true if churchByPerson[a.PersonID] == nil { churchByPerson[a.PersonID] = map[string]int{} } churchByPerson[a.PersonID][s.ChurchID]++ if previous, ok := lastDateByPerson[a.PersonID]; !ok || s.Date.After(previous) { lastDateByPerson[a.PersonID] = s.Date } } for _, a := range working { s, ok := serviceByID[a.ServiceID] if !ok { continue } applyToCounts(a, s) if roleCounts[s.ID] == nil { roleCounts[s.ID] = map[Role]int{} } roleCounts[s.ID][a.Role]++ if rolesByServicePerson[s.ID] == nil { rolesByServicePerson[s.ID] = map[string]map[Role]bool{} } if rolesByServicePerson[s.ID][a.PersonID] == nil { rolesByServicePerson[s.ID][a.PersonID] = map[Role]bool{} } rolesByServicePerson[s.ID][a.PersonID][a.Role] = true } sortedServices := make([]ServiceOccurrence, len(p.Services)) copy(sortedServices, p.Services) sort.SliceStable(sortedServices, func(i, j int) bool { a, b := sortedServices[i], sortedServices[j] if !a.Date.Equal(b.Date) { return a.Date.Before(b.Date) } if a.TimeMinutes != b.TimeMinutes { return a.TimeMinutes < b.TimeMinutes } return a.ID < b.ID }) var unfilled []UnfilledSlot var newAssignments []Assignment for _, service := range sortedServices { assignedRoles := rolesByServicePerson[service.ID] if assignedRoles == nil { assignedRoles = map[string]map[Role]bool{} rolesByServicePerson[service.ID] = assignedRoles } for _, role := range AllRoles { required := service.RequiredCount(role) if required <= 0 { continue } existingForRole := 0 if roleCounts[service.ID] != nil { existingForRole = roleCounts[service.ID][role] } if existingForRole >= required { continue } for i := existingForRole; i < required; i++ { highFeast := highFeastByDate[service.DateKey()] result := p.bestCandidate(service, role, activePeople, absencesByPerson, totalByPerson, monthByPerson, dayServicesByPerson, churchByPerson, lastDateByPerson, assignedRoles, highFeast, true) if result.person == nil { unfilled = append(unfilled, UnfilledSlot{ Service: service, ChurchName: churchNames[service.ChurchID], Role: role, Reason: result.reason, }) continue } person := *result.person assignment := Assignment{ ID: newID(), ServiceID: service.ID, PersonID: person.ID, Role: role, CreatedAt: now(), } newAssignments = append(newAssignments, assignment) working = append(working, assignment) if roleCounts[service.ID] == nil { roleCounts[service.ID] = map[Role]int{} } roleCounts[service.ID][role]++ if assignedRoles[person.ID] == nil { assignedRoles[person.ID] = map[Role]bool{} } assignedRoles[person.ID][role] = true applyToCounts(assignment, service) } } } // Second pass, only on explicit request: use volunteers who agreed to be // planned beyond their preferences for the slots that remained open. if p.Options.AllowBeyondPreferences && len(unfilled) > 0 { var flagged []Person for _, person := range activePeople { if person.AllowBeyondPreferences { flagged = append(flagged, person) } } if len(flagged) > 0 { remaining := make([]UnfilledSlot, 0, len(unfilled)) for _, slot := range unfilled { service := slot.Service highFeast := highFeastByDate[service.DateKey()] assignedRoles := map[string]map[Role]bool{} for _, assignment := range working { if assignment.ServiceID != service.ID { continue } if assignedRoles[assignment.PersonID] == nil { assignedRoles[assignment.PersonID] = map[Role]bool{} } assignedRoles[assignment.PersonID][assignment.Role] = true } result := p.bestCandidate(service, slot.Role, flagged, absencesByPerson, totalByPerson, monthByPerson, dayServicesByPerson, churchByPerson, lastDateByPerson, assignedRoles, highFeast, false) if result.person == nil { slot.Reason = result.reason remaining = append(remaining, slot) continue } person := *result.person assignment := Assignment{ ID: newID(), ServiceID: service.ID, PersonID: person.ID, Role: slot.Role, BeyondPreferences: true, CreatedAt: now(), } newAssignments = append(newAssignments, assignment) working = append(working, assignment) if roleCounts[service.ID] == nil { roleCounts[service.ID] = map[Role]int{} } roleCounts[service.ID][slot.Role]++ applyToCounts(assignment, service) } unfilled = remaining } } filled := len(newAssignments) var message string switch { case filled == 0 && len(unfilled) == 0: message = "Alle Dienste im Zeitraum sind bereits vollständig besetzt." case len(unfilled) == 0: suffix := "e" if filled == 1 { suffix = "" } message = fmt.Sprintf("%d Dienst%s erfolgreich besetzt. Alle Lücken geschlossen.", filled, suffix) default: suffix := "e" if filled == 1 { suffix = "" } gapSuffix := "n" if len(unfilled) == 1 { gapSuffix = "" } message = fmt.Sprintf("%d Dienst%s besetzt, %d Lücke%s bleiben offen.", filled, suffix, len(unfilled), gapSuffix) } if p.Options.ReplaceExisting { var locked []Assignment for _, a := range working { if a.Locked { locked = append(locked, a) } } return PlanResult{Assignments: append(locked, newAssignments...), Unfilled: unfilled, FilledCount: filled, Message: message} } return PlanResult{Assignments: working, Unfilled: unfilled, FilledCount: filled, Message: message} } func (p ServicePlanner) bestCandidate( service ServiceOccurrence, role Role, people []Person, absencesByPerson map[string][]Absence, totalByPerson map[string]int, monthByPerson map[string]int, dayServicesByPerson map[string]map[string]bool, churchByPerson map[string]map[string]int, lastDateByPerson map[string]time.Time, assignedRolesByPerson map[string]map[Role]bool, highFeast bool, enforcePreferences bool, ) candidateResult { blockedReasons := map[string]int{} var eligible []Person for _, person := range people { if !person.CanFill(role) { continue } roles := assignedRolesByPerson[person.ID] if roles != nil && roles[role] { blockedReasons["bereits für diesen Dienst eingeteilt"]++ continue } if absences, ok := absencesByPerson[person.ID]; ok { blocked := false for _, a := range absences { if a.Overlaps(service.Date) { blocked = true break } } if blocked { blockedReasons["abwesend"]++ continue } } if p.Options.RespectPreferredWeekdays && enforcePreferences && !person.MatchesWeekdayPreference(Weekday(service.Date), service.TimeMinutes, highFeast) { blockedReasons["Einsatztag oder Uhrzeit passt nicht"]++ continue } month := MonthKey(service.Date) usedThisMonth := monthByPerson[person.ID+"|"+month] if enforcePreferences && person.MaxPerMonth > 0 && usedThisMonth >= person.MaxPerMonth { blockedReasons["Monatslimit erreicht"]++ continue } usedServices := dayServicesByPerson[person.ID+"|"+service.DateKey()] maxPerDay := p.Options.MaxAssignmentsPerDay if len(usedServices) >= maxPerDay && !subsetOfSingle(usedServices, service.ID) { blockedReasons["bereits an diesem Tag"]++ continue } eligible = append(eligible, person) } minimumTotal := 0 if len(eligible) > 0 { minimumTotal = totalByPerson[eligible[0].ID] for _, person := range eligible[1:] { if totalByPerson[person.ID] < minimumTotal { minimumTotal = totalByPerson[person.ID] } } } const fairnessSlack = 1 var bestPerson *Person bestScore := 0.0 haveBest := false for i := range eligible { person := eligible[i] roles := assignedRolesByPerson[person.ID] total := totalByPerson[person.ID] withinFairnessReach := total-minimumTotal <= fairnessSlack score := 10.0 if withinFairnessReach && roles != nil && roles[role.Complementary()] { score += p.Options.WeightDualRolePreference } else if withinFairnessReach && len(service.RolesNeeded()) > 1 { for _, other := range AllRoles { if other != role && service.RequiredCount(other) > 0 && person.CanFill(other) { score += p.Options.WeightDualRolePreference break } } } if StringContains(person.PreferredChurchIDs, service.ChurchID) { score += p.Options.WeightChurchPreference } if len(person.PreferredChurchIDs) > 0 && !StringContains(person.PreferredChurchIDs, service.ChurchID) { score -= 1.5 } if len(person.PreferredServiceTitles) > 0 { title := strings.ToLower(service.Title) for _, preference := range person.PreferredServiceTitles { if preference != "" && strings.Contains(strings.ToLower(title), strings.ToLower(preference)) { score += p.Options.WeightServicePreference } } } if person.MatchesWeekdayPreference(Weekday(service.Date), service.TimeMinutes, highFeast) && len(person.PreferredWeekdays) > 0 { score += 3 } score -= float64(total) * p.Options.WeightFairness if counts, ok := churchByPerson[person.ID]; ok { score -= float64(counts[service.ChurchID]) * 0.4 } if last, ok := lastDateByPerson[person.ID]; ok { gap := 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 + "|" + string(role)) if !haveBest || score > bestScore { bestScore = score cp := person bestPerson = &cp haveBest = true } } if bestPerson != nil { return candidateResult{person: bestPerson} } reason := "Keine geeignete Person" if len(blockedReasons) == 0 { reason = "Keine geeignete Person mit Rolle " + role.Title() } else { topKey, topCount := "", -1 for key, count := range blockedReasons { if count > topCount { topKey, topCount = key, count } } reason = fmt.Sprintf("%s (%d ausgeschlossen)", topKey, topCount) } return candidateResult{reason: reason} } func subsetOfSingle(set map[string]bool, value string) bool { if len(set) == 0 { return true } if len(set) > 1 { return false } return set[value] } func stableTieBreak(value string) float64 { var hash uint32 = 5381 for _, b := range []byte(value) { hash = (hash << 5) + hash + uint32(b) } return float64(hash%997) / 100000 } // CandidateSuggestions mirrors the macOS detail sheet's suggestion list. func CandidateSuggestions( service ServiceOccurrence, role Role, people []Person, absences []Absence, rangeAssignments []Assignment, services []ServiceOccurrence, serviceAssignments []Assignment, liturgicalDay *LiturgicalDay, ) []CandidateSuggestion { monthKey := MonthKey(service.Date) serviceDateByID := map[string]ServiceOccurrence{} for _, s := range services { serviceDateByID[s.ID] = s } monthlyCounts := map[string]int{} totalCounts := map[string]int{} dayServices := map[string]map[string]bool{} for _, a := range rangeAssignments { s, ok := serviceDateByID[a.ServiceID] if !ok { continue } monthlyCounts[a.PersonID+"|"+MonthKey(s.Date)]++ totalCounts[a.PersonID]++ key := a.PersonID + "|" + s.DateKey() if dayServices[key] == nil { dayServices[key] = map[string]bool{} } dayServices[key][a.ServiceID] = true } assignedRoles := map[string]map[Role]bool{} for _, a := range serviceAssignments { if assignedRoles[a.PersonID] == nil { assignedRoles[a.PersonID] = map[Role]bool{} } assignedRoles[a.PersonID][a.Role] = true } var eligible []Person for _, person := range people { if person.Active && person.CanFill(role) && !(assignedRoles[person.ID] != nil && assignedRoles[person.ID][role]) { eligible = append(eligible, person) } } minimumTotal := 0 if len(eligible) > 0 { minimumTotal = totalCounts[eligible[0].ID] for _, person := range eligible[1:] { if totalCounts[person.ID] < minimumTotal { minimumTotal = totalCounts[person.ID] } } } const fairnessSlack = 1 weekday := Weekday(service.Date) highFeast := liturgicalDay != nil && liturgicalDay.IsHighFeast() var suggestions []CandidateSuggestion for _, person := range eligible { var warnings []string blocked := false beyond := false for _, a := range absences { if a.PersonID == person.ID && a.Overlaps(service.Date) { warnings = append(warnings, "abwesend") blocked = true break } } weekdayMatch := person.MatchesWeekdayPreference(weekday, service.TimeMinutes, highFeast) if !weekdayMatch { // Manual assignments may always override preferences, but the UI // asks for confirmation before doing so. warnings = append(warnings, "Einsatztag oder Uhrzeit passt nicht") beyond = true } if person.MaxPerMonth > 0 && monthlyCounts[person.ID+"|"+monthKey] >= person.MaxPerMonth { warnings = append(warnings, "Monatslimit") beyond = true } used := dayServices[person.ID+"|"+service.DateKey()] if len(used) > 0 && !subsetOfSingle(used, service.ID) { warnings = append(warnings, "bereits an diesem Tag") blocked = true } total := totalCounts[person.ID] within := total-minimumTotal <= fairnessSlack score := 0.0 preferred := false if within && assignedRoles[person.ID] != nil && assignedRoles[person.ID][role.Complementary()] { score += 14 preferred = true } else if within && len(service.RolesNeeded()) > 1 { for _, other := range AllRoles { if other != role && service.RequiredCount(other) > 0 && person.CanFill(other) { score += 14 preferred = true break } } } if StringContains(person.PreferredChurchIDs, service.ChurchID) { score += 8 preferred = true } if len(person.PreferredChurchIDs) > 0 && !StringContains(person.PreferredChurchIDs, service.ChurchID) { score -= 2 } if weekdayMatch && len(person.PreferredWeekdays) > 0 { score += 3 preferred = true } for _, preference := range person.PreferredServiceTitles { if preference != "" && strings.Contains(strings.ToLower(service.Title), strings.ToLower(preference)) { score += 4 preferred = true } } score -= float64(total) * 1.4 for _, a := range absences { if a.PersonID == person.ID && a.Overlaps(service.Date) { score -= 100 break } } suggestions = append(suggestions, CandidateSuggestion{ Person: person, Score: score, Warnings: warnings, Blocked: blocked, Preferred: preferred, BeyondPreferences: beyond, TotalAssignments: total, }) } sort.SliceStable(suggestions, func(i, j int) bool { a, b := suggestions[i], suggestions[j] if a.Blocked != b.Blocked { return !a.Blocked } if a.Score != b.Score { return a.Score > b.Score } return a.Person.LastName < b.Person.LastName }) return suggestions }