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

+184 -25
View File
@@ -2,6 +2,8 @@ package domain
import (
"fmt"
"sort"
"strconv"
"strings"
"time"
)
@@ -89,19 +91,86 @@ type Church struct {
Notes string `json:"notes"`
}
// WeekdayPeriod narrows a preferred weekday to a part of the day.
type WeekdayPeriod string
const (
PeriodAllDay WeekdayPeriod = "all"
PeriodMorning WeekdayPeriod = "morning"
PeriodAfternoon WeekdayPeriod = "afternoon"
PeriodEvening WeekdayPeriod = "evening"
)
var AllWeekdayPeriods = []WeekdayPeriod{PeriodAllDay, PeriodMorning, PeriodAfternoon, PeriodEvening}
func (p WeekdayPeriod) Label() string {
switch p {
case PeriodMorning:
return "vormittags (0–12 Uhr)"
case PeriodAfternoon:
return "nachmittags (12–17 Uhr)"
case PeriodEvening:
return "abends (ab 17 Uhr)"
default:
return "ganztägig"
}
}
func (p WeekdayPeriod) ShortLabel() string {
switch p {
case PeriodMorning:
return "vormittags"
case PeriodAfternoon:
return "nachmittags"
case PeriodEvening:
return "abends"
default:
return "ganztägig"
}
}
func (p WeekdayPeriod) IsValid() bool {
return p == PeriodAllDay || p == PeriodMorning || p == PeriodAfternoon || p == PeriodEvening
}
// Matches reports whether a service starting at timeMinutes falls into the
// selected part of the day. Morning is 0–12, afternoon 12–17, evening after 17.
func (p WeekdayPeriod) Matches(timeMinutes int) bool {
switch p {
case PeriodMorning:
return timeMinutes < 12*60
case PeriodAfternoon:
return timeMinutes >= 12*60 && timeMinutes < 17*60
case PeriodEvening:
return timeMinutes >= 17*60
default:
return true
}
}
// WeekdayPeriodPreference stores the selected part of the day for one
// preferred weekday. Weekdays without an entry count as all day.
type WeekdayPeriodPreference struct {
Weekday int `json:"weekday"`
Period WeekdayPeriod `json:"period"`
}
type Person struct {
ID string `json:"id"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Roles []Role `json:"roles"`
Email string `json:"email"`
EmailLocked bool `json:"-"`
PreferredChurchIDs []string `json:"preferredChurchIDs"`
PreferredWeekdays []int `json:"preferredWeekdays"`
PreferredServiceTitles []string `json:"preferredServiceTitles"`
MaxPerMonth int `json:"maxPerMonth"`
Active bool `json:"active"`
Notes string `json:"notes"`
ID string `json:"id"`
ShortCode string `json:"shortCode"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Roles []Role `json:"roles"`
Email string `json:"email"`
EmailLocked bool `json:"-"`
PreferredChurchIDs []string `json:"preferredChurchIDs"`
PreferredWeekdays []int `json:"preferredWeekdays"`
PreferredWeekdayPeriods []WeekdayPeriodPreference `json:"preferredWeekdayPeriods"`
PreferredServiceTitles []string `json:"preferredServiceTitles"`
MaxPerMonth int `json:"maxPerMonth"`
AllowBeyondPreferences bool `json:"allowBeyondPreferences"`
Active bool `json:"active"`
Notes string `json:"notes"`
}
func (p Person) FullName() string {
@@ -127,6 +196,80 @@ func (p Person) AbbreviatedName() string {
return p.LastName
}
// DisplayShort is the guest-facing label: an explicitly maintained Kürzel wins,
// otherwise the initials from first and last name.
func (p Person) DisplayShort() string {
if code := strings.TrimSpace(p.ShortCode); code != "" {
return code
}
return p.Initials()
}
// WeekdayPeriodFor returns the selected part of the day for a weekday.
func (p Person) WeekdayPeriodFor(weekday int) WeekdayPeriod {
for _, preference := range p.PreferredWeekdayPeriods {
if preference.Weekday == weekday && preference.Period.IsValid() {
return preference.Period
}
}
return PeriodAllDay
}
// MatchesWeekdayPreference reports whether the service day and time satisfy
// the weekday preferences. High feasts count like Sundays, so a Sunday
// preference also covers them. An empty weekday list means no restriction.
func (p Person) MatchesWeekdayPreference(weekday, timeMinutes int, highFeast bool) bool {
if len(p.PreferredWeekdays) == 0 {
return true
}
candidates := []int{weekday}
if highFeast && weekday != 1 {
candidates = append(candidates, 1)
}
for _, day := range candidates {
if IntContains(p.PreferredWeekdays, day) && p.WeekdayPeriodFor(day).Matches(timeMinutes) {
return true
}
}
return false
}
// PreferenceNote is the free-text planning note shown next to assignments.
func (p Person) PreferenceNote() string { return strings.TrimSpace(p.Notes) }
// PersonLabels computes stable short labels for a set of people. If two people
// share a label, every member of that group gets a running number appended.
func PersonLabels(people []Person) map[string]string {
sorted := append([]Person(nil), people...)
sort.SliceStable(sorted, func(i, j int) bool {
if sorted[i].LastName != sorted[j].LastName {
return sorted[i].LastName < sorted[j].LastName
}
if sorted[i].FirstName != sorted[j].FirstName {
return sorted[i].FirstName < sorted[j].FirstName
}
return sorted[i].ID < sorted[j].ID
})
base := make(map[string]string, len(sorted))
counts := map[string]int{}
for _, person := range sorted {
label := person.DisplayShort()
base[person.ID] = label
counts[label]++
}
seen := map[string]int{}
labels := make(map[string]string, len(sorted))
for _, person := range sorted {
label := base[person.ID]
if counts[label] > 1 {
seen[label]++
label += strconv.Itoa(seen[label])
}
labels[person.ID] = label
}
return labels
}
func (p Person) RoleLabel() string {
var parts []string
for _, role := range AllRoles {
@@ -336,13 +479,14 @@ func (s ServiceOccurrence) RolesNeeded() []Role {
}
type Assignment struct {
ID string `json:"id"`
ServiceID string `json:"serviceID"`
PersonID string `json:"personID"`
Role Role `json:"role"`
Locked bool `json:"locked"`
Note string `json:"note"`
CreatedAt time.Time `json:"createdAt"`
ID string `json:"id"`
ServiceID string `json:"serviceID"`
PersonID string `json:"personID"`
Role Role `json:"role"`
Locked bool `json:"locked"`
BeyondPreferences bool `json:"beyondPreferences"`
Note string `json:"note"`
CreatedAt time.Time `json:"createdAt"`
}
// Liturgical model ---------------------------------------------------------
@@ -702,6 +846,19 @@ func (r DayPlanRow) AssignmentCount() int {
}
func (r DayPlanRow) HasServices() bool { return len(r.Services) > 0 }
// HasBeyondPreferences marks days with at least one assignment that goes
// beyond the person's preferences.
func (r DayPlanRow) HasBeyondPreferences() bool {
for _, service := range r.Services {
for _, assignment := range service.Assignments {
if assignment.BeyondPreferences {
return true
}
}
}
return false
}
func (r DayPlanRow) IsSunday() bool {
return (r.LiturgicalDay != nil && r.LiturgicalDay.IsSunday()) || IsSunday(r.Date)
}
@@ -823,6 +980,7 @@ func (s RangeStatistics) AverageAssignments() float64 {
type PlannerOptions struct {
ReplaceExisting bool
RespectPreferredWeekdays bool
AllowBeyondPreferences bool
AllowDoubleRolesOnSameDay bool
WeightChurchPreference float64
WeightServicePreference float64
@@ -850,10 +1008,11 @@ type PlanResult struct {
}
type CandidateSuggestion struct {
Person Person
Score float64
Warnings []string
Blocked bool
Preferred bool
TotalAssignments int
Person Person
Score float64
Warnings []string
Blocked bool
Preferred bool
BeyondPreferences bool
TotalAssignments int
}
+93 -13
View File
@@ -14,6 +14,7 @@ type ServicePlanner struct {
Services []ServiceOccurrence
ExistingAssignments []Assignment
Churches []Church
LiturgicalDays []LiturgicalDay
Options PlannerOptions
}
@@ -41,6 +42,12 @@ func (p ServicePlanner) Plan() PlanResult {
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 {
@@ -129,9 +136,10 @@ func (p ServicePlanner) Plan() PlanResult {
continue
}
for i := existingForRole; i < required; i++ {
highFeast := highFeastByDate[service.DateKey()]
result := p.bestCandidate(service, role, activePeople, absencesByPerson,
totalByPerson, monthByPerson, dayServicesByPerson, churchByPerson,
lastDateByPerson, assignedRoles)
lastDateByPerson, assignedRoles, highFeast, true)
if result.person == nil {
unfilled = append(unfilled, UnfilledSlot{
Service: service,
@@ -165,6 +173,59 @@ func (p ServicePlanner) Plan() PlanResult {
}
}
// 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 {
@@ -211,6 +272,8 @@ func (p ServicePlanner) bestCandidate(
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
@@ -237,14 +300,14 @@ func (p ServicePlanner) bestCandidate(
continue
}
}
if p.Options.RespectPreferredWeekdays && len(person.PreferredWeekdays) > 0 &&
!IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
blockedReasons["Einsatztag passt nicht"]++
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 person.MaxPerMonth > 0 && usedThisMonth >= person.MaxPerMonth {
if enforcePreferences && person.MaxPerMonth > 0 && usedThisMonth >= person.MaxPerMonth {
blockedReasons["Monatslimit erreicht"]++
continue
}
@@ -303,7 +366,8 @@ func (p ServicePlanner) bestCandidate(
}
}
}
if IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
if person.MatchesWeekdayPreference(Weekday(service.Date), service.TimeMinutes, highFeast) &&
len(person.PreferredWeekdays) > 0 {
score += 3
}
score -= float64(total) * p.Options.WeightFairness
@@ -377,6 +441,7 @@ func CandidateSuggestions(
services []ServiceOccurrence,
serviceAssignments []Assignment,
ignorePreferredWeekdays bool,
liturgicalDay *LiturgicalDay,
) []CandidateSuggestion {
monthKey := MonthKey(service.Date)
serviceDateByID := map[string]ServiceOccurrence{}
@@ -424,11 +489,13 @@ func CandidateSuggestions(
}
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")
@@ -436,13 +503,26 @@ func CandidateSuggestions(
break
}
}
if !ignorePreferredWeekdays && len(person.PreferredWeekdays) > 0 && !IntContains(person.PreferredWeekdays, weekday) {
warnings = append(warnings, "Einsatztag passt nicht")
blocked = true
weekdayMatch := person.MatchesWeekdayPreference(weekday, service.TimeMinutes, highFeast)
if !weekdayMatch {
switch {
case ignorePreferredWeekdays:
beyond = true
case person.AllowBeyondPreferences:
beyond = true
default:
warnings = append(warnings, "Einsatztag oder Uhrzeit passt nicht")
blocked = true
}
}
if person.MaxPerMonth > 0 && monthlyCounts[person.ID+"|"+monthKey] >= person.MaxPerMonth {
warnings = append(warnings, "Monatslimit")
blocked = true
if person.AllowBeyondPreferences {
warnings = append(warnings, "Monatslimit")
beyond = true
} else {
warnings = append(warnings, "Monatslimit")
blocked = true
}
}
used := dayServices[person.ID+"|"+service.DateKey()]
if len(used) > 0 && !subsetOfSingle(used, service.ID) {
@@ -473,7 +553,7 @@ func CandidateSuggestions(
if len(person.PreferredChurchIDs) > 0 && !StringContains(person.PreferredChurchIDs, service.ChurchID) {
score -= 2
}
if IntContains(person.PreferredWeekdays, weekday) {
if weekdayMatch && len(person.PreferredWeekdays) > 0 {
score += 3
preferred = true
}
@@ -492,7 +572,7 @@ func CandidateSuggestions(
}
suggestions = append(suggestions, CandidateSuggestion{
Person: person, Score: score, Warnings: warnings, Blocked: blocked,
Preferred: preferred, TotalAssignments: total,
Preferred: preferred, BeyondPreferences: beyond, TotalAssignments: total,
})
}
+157
View File
@@ -0,0 +1,157 @@
package domain
import "testing"
func TestPersonLabelsUsesShortCodeAndNumbersDuplicates(t *testing.T) {
people := []Person{
{ID: "p1", FirstName: "Anna", LastName: "Berg"},
{ID: "p2", FirstName: "Anton", LastName: "Berg"},
{ID: "p3", ShortCode: "MK", FirstName: "Markus", LastName: "Klein"},
{ID: "p4", FirstName: "Mia", LastName: "Sommer"},
}
labels := PersonLabels(people)
cases := map[string]string{"p1": "AB1", "p2": "AB2", "p3": "MK", "p4": "MS"}
for id, want := range cases {
if got := labels[id]; got != want {
t.Errorf("label for %s = %q, want %q", id, got, want)
}
}
}
func TestMatchesWeekdayPreferenceTreatsHighFeastsLikeSundays(t *testing.T) {
sundayOnly := Person{PreferredWeekdays: []int{1}}
if !sundayOnly.MatchesWeekdayPreference(2, 10*60, true) {
t.Fatal("a Sunday preference must cover a high feast on another weekday")
}
if sundayOnly.MatchesWeekdayPreference(2, 10*60, false) {
t.Fatal("an ordinary Monday must not match a Sunday preference")
}
morningSunday := Person{
PreferredWeekdays: []int{1},
PreferredWeekdayPeriods: []WeekdayPeriodPreference{
{Weekday: 1, Period: PeriodMorning},
},
}
if !morningSunday.MatchesWeekdayPreference(2, 10*60, true) {
t.Fatal("a high feast in the morning should match the Sunday morning preference")
}
if morningSunday.MatchesWeekdayPreference(2, 18*60, true) {
t.Fatal("a high feast in the evening must not match the Sunday morning preference")
}
}
func TestMatchesWeekdayPreferenceUsesPeriodBounds(t *testing.T) {
person := Person{
PreferredWeekdays: []int{2},
PreferredWeekdayPeriods: []WeekdayPeriodPreference{
{Weekday: 2, Period: PeriodMorning},
},
}
if !person.MatchesWeekdayPreference(2, 11*60+59, false) {
t.Error("11:59 belongs to the morning")
}
if person.MatchesWeekdayPreference(2, 12*60, false) {
t.Error("12:00 must no longer count as morning")
}
if person.MatchesWeekdayPreference(2, 16*60+59, false) {
t.Error("16:59 belongs to the afternoon, not the morning")
}
person.PreferredWeekdayPeriods = []WeekdayPeriodPreference{{Weekday: 2, Period: PeriodEvening}}
if !person.MatchesWeekdayPreference(2, 17*60, false) {
t.Error("17:00 belongs to the evening")
}
}
func plannerFixture(person Person) (ServicePlanner, ServiceOccurrence) {
church := Church{ID: "c1", Name: "St. Andreas"}
// 2026-11-16 is a Monday.
service := ServiceOccurrence{
ID: "s1", ChurchID: church.ID, Date: MustDate("2026-11-16"),
TimeMinutes: 18 * 60, Title: "Abendmesse", LectorsNeeded: 1,
}
planner := ServicePlanner{
People: []Person{person},
Services: []ServiceOccurrence{service},
Churches: []Church{church},
Options: DefaultPlannerOptions(),
}
return planner, service
}
func TestPlannerBeyondPreferencesRequiresExplicitPass(t *testing.T) {
person := Person{
ID: "p1", FirstName: "Anna", LastName: "Berg", Roles: []Role{RoleLector},
PreferredWeekdays: []int{1}, Active: true, MaxPerMonth: 1,
}
planner, _ := plannerFixture(person)
planner.Options.RespectPreferredWeekdays = true
result := planner.Plan()
if len(result.Unfilled) != 1 || len(result.Assignments) != 0 {
t.Fatalf("without permission the slot must stay open, got %#v", result)
}
person.AllowBeyondPreferences = true
planner, _ = plannerFixture(person)
planner.Options.RespectPreferredWeekdays = true
planner.Options.AllowBeyondPreferences = true
result = planner.Plan()
if len(result.Unfilled) != 0 || len(result.Assignments) != 1 {
t.Fatalf("expected a fallback assignment, got %#v", result)
}
if !result.Assignments[0].BeyondPreferences {
t.Fatal("fallback assignment must be marked as beyond preferences")
}
person.AllowBeyondPreferences = false
planner, _ = plannerFixture(person)
planner.Options.AllowBeyondPreferences = true
if result := planner.Plan(); len(result.Assignments) != 0 {
t.Fatal("a person without permission must not be planned beyond preferences")
}
}
func TestPlannerTreatsHighFeastAsSunday(t *testing.T) {
person := Person{
ID: "p1", FirstName: "Anna", LastName: "Berg", Roles: []Role{RoleLector},
PreferredWeekdays: []int{1}, Active: true, MaxPerMonth: 6,
}
planner, service := plannerFixture(person)
planner.LiturgicalDays = []LiturgicalDay{{
Date: service.Date, Title: "Hochfest", Rank: RankSolemnity,
}}
result := planner.Plan()
if len(result.Assignments) != 1 || len(result.Unfilled) != 0 {
t.Fatalf("high feast must match a Sunday preference, got %#v", result)
}
if result.Assignments[0].BeyondPreferences {
t.Fatal("a matched high feast is not beyond preferences")
}
}
func TestCandidateSuggestionsMarkBeyondPreferences(t *testing.T) {
service := ServiceOccurrence{
ID: "s1", ChurchID: "c1", Date: MustDate("2026-11-16"),
TimeMinutes: 18 * 60, Title: "Abendmesse", LectorsNeeded: 1,
}
sundayOnly := Person{
ID: "p1", FirstName: "Anna", LastName: "Berg", Roles: []Role{RoleLector},
PreferredWeekdays: []int{1}, Active: true, MaxPerMonth: 6,
}
suggestions := CandidateSuggestions(service, RoleLector,
[]Person{sundayOnly}, nil, nil, []ServiceOccurrence{service}, nil, false, nil)
if len(suggestions) != 1 || !suggestions[0].Blocked || suggestions[0].BeyondPreferences {
t.Fatalf("person without permission should be blocked, got %#v", suggestions)
}
sundayOnly.AllowBeyondPreferences = true
suggestions = CandidateSuggestions(service, RoleLector,
[]Person{sundayOnly}, nil, nil, []ServiceOccurrence{service}, nil, false, nil)
if len(suggestions) != 1 || suggestions[0].Blocked || !suggestions[0].BeyondPreferences {
t.Fatalf("flagged person should be suggested beyond preferences, got %#v", suggestions)
}
if suggestions[0].Person.PreferenceNote() != "" {
t.Fatal("unexpected preference note")
}
}