Web Variante in Go V0.1
This commit is contained in:
1 parent
f9e3e94629
commit
692b9b6ef8
60 files changed
+13140
No files matched your search
@@ -0,0 +1,290 @@
|
||||
// Package domain contains the planning rules shared by the web application.
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// All app dates are calendar days anchored at noon in the Europe/Berlin time
|
||||
// zone. Noon avoids daylight-saving surprises while the ISO key stays stable.
|
||||
var Berlin = loadBerlin()
|
||||
|
||||
func loadBerlin() *time.Location {
|
||||
if loc, err := time.LoadLocation("Europe/Berlin"); err == nil {
|
||||
return loc
|
||||
}
|
||||
return time.UTC
|
||||
}
|
||||
|
||||
func Normalize(t time.Time) time.Time {
|
||||
y, m, d := t.In(Berlin).Date()
|
||||
return time.Date(y, m, d, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func Today() time.Time {
|
||||
return Normalize(time.Now())
|
||||
}
|
||||
|
||||
func DateFromKey(key string) (time.Time, bool) {
|
||||
t, err := time.ParseInLocation("2006-01-02", key, Berlin)
|
||||
if err != nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return Normalize(t), true
|
||||
}
|
||||
|
||||
func MustDate(key string) time.Time {
|
||||
t, ok := DateFromKey(key)
|
||||
if !ok {
|
||||
return Today()
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func Key(t time.Time) string {
|
||||
return t.In(Berlin).Format("2006-01-02")
|
||||
}
|
||||
|
||||
func KeyYMD(year, month, day int) string {
|
||||
return fmt.Sprintf("%04d-%02d-%02d", year, month, day)
|
||||
}
|
||||
|
||||
func AddingDays(days int, t time.Time) time.Time {
|
||||
return Normalize(Normalize(t).AddDate(0, 0, days))
|
||||
}
|
||||
|
||||
func AddingMonths(months int, t time.Time) time.Time {
|
||||
t = Normalize(t)
|
||||
y, m, d := t.Date()
|
||||
first := time.Date(y, m, 1, 12, 0, 0, 0, Berlin).AddDate(0, months, 0)
|
||||
last := first.AddDate(0, 1, -1)
|
||||
if d > last.Day() {
|
||||
d = last.Day()
|
||||
}
|
||||
return time.Date(first.Year(), first.Month(), d, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func AddingYears(years int, t time.Time) time.Time {
|
||||
t = Normalize(t)
|
||||
return time.Date(t.Year()+years, t.Month(), t.Day(), 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func ordinal(t time.Time) int64 {
|
||||
y, m, d := Normalize(t).Date()
|
||||
return time.Date(y, m, d, 0, 0, 0, 0, time.UTC).Unix() / 86400
|
||||
}
|
||||
|
||||
func DaysBetween(start, end time.Time) int {
|
||||
return int(ordinal(end) - ordinal(start))
|
||||
}
|
||||
|
||||
func DaysInRange(r DayRange) []time.Time {
|
||||
if r.Start.After(r.End) {
|
||||
return nil
|
||||
}
|
||||
var result []time.Time
|
||||
for cursor := Normalize(r.Start); !cursor.After(r.End); cursor = AddingDays(1, cursor) {
|
||||
result = append(result, cursor)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Weekday follows the Swift app's convention: 1 = Sunday … 7 = Saturday.
|
||||
func Weekday(t time.Time) int {
|
||||
return int(Normalize(t).Weekday()) + 1
|
||||
}
|
||||
|
||||
func IsSunday(t time.Time) bool { return Weekday(t) == 1 }
|
||||
func IsSaturday(t time.Time) bool { return Weekday(t) == 7 }
|
||||
|
||||
var weekdayNames = []string{"", "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"}
|
||||
var shortWeekdayNames = []string{"", "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"}
|
||||
var monthNames = []string{"", "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}
|
||||
var shortMonthNames = []string{"", "Jan.", "Feb.", "März", "Apr.", "Mai", "Juni", "Juli", "Aug.", "Sept.", "Okt.", "Nov.", "Dez."}
|
||||
|
||||
func WeekdayName(t time.Time) string { return weekdayNames[Weekday(t)] }
|
||||
func ShortWeekdayName(t time.Time) string { return shortWeekdayNames[Weekday(t)] }
|
||||
func MonthName(t time.Time) string { return monthNames[int(Normalize(t).Month())] }
|
||||
func ShortMonthName(t time.Time) string { return shortMonthNames[int(Normalize(t).Month())] }
|
||||
|
||||
func LongString(t time.Time) string {
|
||||
return fmt.Sprintf("%s, %d. %s %d", WeekdayName(t), DayNumber(t), MonthName(t), Year(t))
|
||||
}
|
||||
|
||||
func MediumString(t time.Time) string {
|
||||
return fmt.Sprintf("%d. %s %d", DayNumber(t), ShortMonthName(t), Year(t))
|
||||
}
|
||||
|
||||
func DayNumber(t time.Time) int { return Normalize(t).Day() }
|
||||
func Month(t time.Time) int { return int(Normalize(t).Month()) }
|
||||
func Year(t time.Time) int { return Normalize(t).Year() }
|
||||
|
||||
func StartOfYear(t time.Time) time.Time {
|
||||
return time.Date(Year(t), 1, 1, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func EndOfYear(t time.Time) time.Time {
|
||||
return time.Date(Year(t), 12, 31, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func StartOfMonth(t time.Time) time.Time {
|
||||
y, m, _ := Normalize(t).Date()
|
||||
return time.Date(y, m, 1, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func EndOfMonth(t time.Time) time.Time {
|
||||
return AddingDays(-1, AddingMonths(1, StartOfMonth(t)))
|
||||
}
|
||||
|
||||
func StartOfQuarter(t time.Time) time.Time {
|
||||
m := Month(t)
|
||||
quarterStart := ((m-1)/3)*3 + 1
|
||||
return time.Date(Year(t), time.Month(quarterStart), 1, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func EndOfQuarter(t time.Time) time.Time {
|
||||
return AddingDays(-1, AddingMonths(3, StartOfQuarter(t)))
|
||||
}
|
||||
|
||||
func Quarter(t time.Time) int { return (Month(t)-1)/3 + 1 }
|
||||
|
||||
func MonthKey(t time.Time) string {
|
||||
return fmt.Sprintf("%04d-%02d", Year(t), Month(t))
|
||||
}
|
||||
|
||||
func TimeString(minutes int) string {
|
||||
if minutes < 0 {
|
||||
minutes = 0
|
||||
}
|
||||
h := minutes / 60
|
||||
m := minutes % 60
|
||||
if h > 23 {
|
||||
h = 23
|
||||
}
|
||||
if m > 59 {
|
||||
m = 59
|
||||
}
|
||||
return fmt.Sprintf("%02d:%02d", h, m)
|
||||
}
|
||||
|
||||
func Minutes(hour, minute int) int { return hour*60 + minute }
|
||||
|
||||
func ParseTimeString(s string) (int, bool) {
|
||||
var h, m int
|
||||
if _, err := fmt.Sscanf(strings.TrimSpace(s), "%d:%d", &h, &m); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
if h < 0 || h > 23 || m < 0 || m > 59 {
|
||||
return 0, false
|
||||
}
|
||||
return h*60 + m, true
|
||||
}
|
||||
|
||||
// DayRange is an inclusive calendar-day range.
|
||||
type DayRange struct {
|
||||
Start time.Time
|
||||
End time.Time
|
||||
}
|
||||
|
||||
func NewDayRange(start, end time.Time) DayRange {
|
||||
a, b := Normalize(start), Normalize(end)
|
||||
if a.After(b) {
|
||||
a, b = b, a
|
||||
}
|
||||
return DayRange{Start: a, End: b}
|
||||
}
|
||||
|
||||
func RangeFromKeys(startKey, endKey string) DayRange {
|
||||
start := MustDate(startKey)
|
||||
end, ok := DateFromKey(endKey)
|
||||
if !ok {
|
||||
end = start
|
||||
}
|
||||
return NewDayRange(start, end)
|
||||
}
|
||||
|
||||
func QuarterRange(date time.Time) DayRange {
|
||||
return NewDayRange(StartOfQuarter(date), EndOfQuarter(date))
|
||||
}
|
||||
|
||||
func YearRange(year int) DayRange {
|
||||
return NewDayRange(MustDate(KeyYMD(year, 1, 1)), MustDate(KeyYMD(year, 12, 31)))
|
||||
}
|
||||
|
||||
func MonthRange(date time.Time) DayRange {
|
||||
return NewDayRange(StartOfMonth(date), EndOfMonth(date))
|
||||
}
|
||||
|
||||
func DaysRange(count int, from time.Time) DayRange {
|
||||
if count < 1 {
|
||||
count = 1
|
||||
}
|
||||
return NewDayRange(from, AddingDays(count-1, from))
|
||||
}
|
||||
|
||||
func (r DayRange) Days() []time.Time { return DaysInRange(r) }
|
||||
func (r DayRange) DayCount() int { return DaysBetween(r.Start, r.End) + 1 }
|
||||
func (r DayRange) Contains(t time.Time) bool {
|
||||
d := Normalize(t)
|
||||
return !d.Before(r.Start) && !d.After(r.End)
|
||||
}
|
||||
func (r DayRange) MonthCount() int {
|
||||
return (Year(r.End)-Year(r.Start))*12 + Month(r.End) - Month(r.Start) + 1
|
||||
}
|
||||
|
||||
func (r DayRange) Title() string {
|
||||
return MediumString(r.Start) + " – " + MediumString(r.End)
|
||||
}
|
||||
|
||||
func (r DayRange) ShortTitle() string {
|
||||
startLabel := fmt.Sprintf("%d. %s", DayNumber(r.Start), ShortMonthName(r.Start))
|
||||
endLabel := fmt.Sprintf("%d. %s", DayNumber(r.End), ShortMonthName(r.End))
|
||||
if Year(r.Start) == Year(r.End) {
|
||||
return fmt.Sprintf("%s – %s %d", startLabel, endLabel, Year(r.End))
|
||||
}
|
||||
return fmt.Sprintf("%s %d – %s %d", startLabel, Year(r.Start), endLabel, Year(r.End))
|
||||
}
|
||||
|
||||
func (r DayRange) LongTitle() string {
|
||||
return fmt.Sprintf("%s bis %s · %d Tage", LongString(r.Start), LongString(r.End), r.DayCount())
|
||||
}
|
||||
|
||||
func (r DayRange) Clamped(bounds DayRange) DayRange {
|
||||
start, end := r.Start, r.End
|
||||
if start.Before(bounds.Start) {
|
||||
start = bounds.Start
|
||||
}
|
||||
if end.After(bounds.End) {
|
||||
end = bounds.End
|
||||
}
|
||||
if end.Before(start) {
|
||||
end = start
|
||||
}
|
||||
return NewDayRange(start, end)
|
||||
}
|
||||
|
||||
func (r DayRange) Extend(monthsBefore, monthsAfter int) DayRange {
|
||||
return NewDayRange(AddingMonths(-monthsBefore, r.Start), AddingMonths(monthsAfter, r.End))
|
||||
}
|
||||
|
||||
// CurrentChurchYear returns the liturgical year containing the date.
|
||||
func CurrentChurchYear(date time.Time) DayRange {
|
||||
y := Year(date)
|
||||
thisAdvent := AdventStart(y)
|
||||
if date.Before(thisAdvent) {
|
||||
return NewDayRange(AdventStart(y-1), ChristKing(y))
|
||||
}
|
||||
return NewDayRange(thisAdvent, ChristKing(y+1))
|
||||
}
|
||||
|
||||
func SortedKeys(m map[string]int) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Liturgical calendar primitives shared by the store, the local fallback and
|
||||
// the web views.
|
||||
|
||||
func EasterSunday(year int) time.Time {
|
||||
a := year % 19
|
||||
b := year / 100
|
||||
c := year % 100
|
||||
d := b / 4
|
||||
e := b % 4
|
||||
f := (b + 8) / 25
|
||||
g := (b - f + 1) / 3
|
||||
h := (19*a + b - d - g + 15) % 30
|
||||
i := c / 4
|
||||
k := c % 4
|
||||
l := (32 + 2*e + 2*i - h - k) % 7
|
||||
m := (a + 11*h + 22*l) / 451
|
||||
month := (h + l - 7*m + 114) / 31
|
||||
day := ((h + l - 7*m + 114) % 31) + 1
|
||||
return MustDate(KeyYMD(year, month, day))
|
||||
}
|
||||
|
||||
func easterOffset(offset, year int) time.Time {
|
||||
return AddingDays(offset, EasterSunday(year))
|
||||
}
|
||||
|
||||
func AshWednesday(year int) time.Time { return easterOffset(-46, year) }
|
||||
func PalmSunday(year int) time.Time { return easterOffset(-7, year) }
|
||||
func HolyThursday(year int) time.Time { return easterOffset(-3, year) }
|
||||
func GoodFriday(year int) time.Time { return easterOffset(-2, year) }
|
||||
func HolySaturday(year int) time.Time { return easterOffset(-1, year) }
|
||||
func Ascension(year int) time.Time { return easterOffset(39, year) }
|
||||
func Pentecost(year int) time.Time { return easterOffset(49, year) }
|
||||
func CorpusChristi(year int) time.Time { return easterOffset(60, year) }
|
||||
func SacredHeart(year int) time.Time { return easterOffset(68, year) }
|
||||
func TrinitySunday(year int) time.Time { return easterOffset(56, year) }
|
||||
|
||||
// AdventStart returns the first Sunday of Advent in the given year.
|
||||
func AdventStart(year int) time.Time {
|
||||
christmasEve := MustDate(KeyYMD(year, 12, 24))
|
||||
sunday := christmasEve
|
||||
for Weekday(sunday) != 1 {
|
||||
sunday = AddingDays(-1, sunday)
|
||||
}
|
||||
return AddingDays(-21, sunday)
|
||||
}
|
||||
|
||||
// ChristKing returns the feast of Christ the King for the given year.
|
||||
func ChristKing(year int) time.Time { return AddingDays(-7, AdventStart(year)) }
|
||||
|
||||
// BaptismOfTheLord returns the end of the Christmas season.
|
||||
func BaptismOfTheLord(year int) time.Time {
|
||||
epiphany := MustDate(KeyYMD(year, 1, 6))
|
||||
sunday := AddingDays(1, epiphany)
|
||||
for Weekday(sunday) != 1 {
|
||||
sunday = AddingDays(1, sunday)
|
||||
}
|
||||
if Month(epiphany) == 1 && DayNumber(epiphany) >= 7 {
|
||||
return AddingDays(1, epiphany)
|
||||
}
|
||||
return sunday
|
||||
}
|
||||
|
||||
// SeasonFor maps a date onto the liturgical season.
|
||||
func SeasonFor(date time.Time) LiturgicalSeason {
|
||||
day := Normalize(date)
|
||||
y := Year(day)
|
||||
advent := AdventStart(y)
|
||||
christmas := MustDate(KeyYMD(y, 12, 25))
|
||||
baptism := BaptismOfTheLord(y)
|
||||
ash := AshWednesday(y)
|
||||
holyThursday := HolyThursday(y)
|
||||
easter := EasterSunday(y)
|
||||
pentecost := Pentecost(y)
|
||||
|
||||
switch {
|
||||
case !day.Before(advent) && day.Before(christmas):
|
||||
return SeasonAdvent
|
||||
case !day.Before(christmas) || !day.After(baptism):
|
||||
return SeasonChristmas
|
||||
case !day.Before(ash) && day.Before(holyThursday):
|
||||
return SeasonLent
|
||||
case !day.Before(easter) && !day.After(pentecost):
|
||||
return SeasonEaster
|
||||
case day.After(pentecost) && day.Before(advent):
|
||||
return SeasonOrdinary
|
||||
default:
|
||||
return SeasonOrdinary
|
||||
}
|
||||
}
|
||||
|
||||
// SymbolFor picks a decorative feast symbol from the title and rank.
|
||||
func SymbolFor(title string, rank LiturgicalRank, date time.Time) FeastSymbol {
|
||||
t := strings.ToLower(title)
|
||||
switch {
|
||||
case strings.Contains(t, "weihnacht"), strings.Contains(t, "geburt des herrn"), strings.Contains(t, "erscheinung"):
|
||||
return FeastStar
|
||||
case strings.Contains(t, "ostern"), strings.Contains(t, "auferstehung"):
|
||||
return FeastSun
|
||||
case strings.Contains(t, "pfingst"), strings.Contains(t, "heiliger geist"):
|
||||
return FeastFlame
|
||||
case strings.Contains(t, "fronleichnam"), strings.Contains(t, "abendmahl"), strings.Contains(t, "gründonnerstag"):
|
||||
return FeastCandle
|
||||
case strings.Contains(t, "herz jesu"):
|
||||
return FeastHeart
|
||||
case strings.Contains(t, "christkönig"), strings.Contains(t, "allerheiligen"):
|
||||
return FeastCrown
|
||||
case strings.Contains(t, "maria"), strings.Contains(t, "mariä"):
|
||||
return FeastLily
|
||||
case strings.Contains(t, "kreuz"), strings.Contains(t, "kreuzerhöhung"):
|
||||
return FeastCross
|
||||
case strings.Contains(t, "taufe"):
|
||||
return FeastDove
|
||||
case strings.Contains(t, "wort gottes"), strings.Contains(t, "evangel"):
|
||||
return FeastBook
|
||||
case strings.Contains(t, "lichtmess"), strings.Contains(t, "darstellung"):
|
||||
return FeastCandle
|
||||
}
|
||||
if rank == RankSolemnity || rank == RankFeast {
|
||||
return FeastCross
|
||||
}
|
||||
return FeastBook
|
||||
}
|
||||
@@ -0,0 +1,859 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Role is a service role. Lector and helper do not exclude each other.
|
||||
type Role string
|
||||
|
||||
const (
|
||||
RoleLector Role = "lector"
|
||||
RoleHelper Role = "helper"
|
||||
)
|
||||
|
||||
var AllRoles = []Role{RoleLector, RoleHelper}
|
||||
|
||||
func (r Role) Title() string {
|
||||
if r == RoleHelper {
|
||||
return "Kommunionhelfer"
|
||||
}
|
||||
return "Lektor"
|
||||
}
|
||||
|
||||
func (r Role) Plural() string {
|
||||
if r == RoleHelper {
|
||||
return "Kommunionhelfer"
|
||||
}
|
||||
return "Lektoren"
|
||||
}
|
||||
|
||||
func (r Role) ShortCode() string {
|
||||
if r == RoleHelper {
|
||||
return "K"
|
||||
}
|
||||
return "L"
|
||||
}
|
||||
|
||||
func (r Role) Complementary() Role {
|
||||
if r == RoleLector {
|
||||
return RoleHelper
|
||||
}
|
||||
return RoleLector
|
||||
}
|
||||
|
||||
func (r Role) IsValid() bool { return r == RoleLector || r == RoleHelper }
|
||||
|
||||
type ChurchSymbol string
|
||||
|
||||
const (
|
||||
SymbolBasilica ChurchSymbol = "basilica"
|
||||
SymbolGothic ChurchSymbol = "gothic"
|
||||
SymbolModern ChurchSymbol = "modern"
|
||||
SymbolRotunda ChurchSymbol = "rotunda"
|
||||
SymbolRoundTower ChurchSymbol = "roundTower"
|
||||
SymbolChapel ChurchSymbol = "chapel"
|
||||
)
|
||||
|
||||
var AllChurchSymbols = []ChurchSymbol{
|
||||
SymbolBasilica, SymbolGothic, SymbolModern, SymbolRotunda, SymbolRoundTower, SymbolChapel,
|
||||
}
|
||||
|
||||
func (s ChurchSymbol) Caption() string {
|
||||
switch s {
|
||||
case SymbolBasilica:
|
||||
return "Romanische Basilika"
|
||||
case SymbolGothic:
|
||||
return "Neugotische Kirche"
|
||||
case SymbolModern:
|
||||
return "Moderner Kirchenbau"
|
||||
case SymbolRotunda:
|
||||
return "Rundkirche"
|
||||
case SymbolRoundTower:
|
||||
return "Rundturm"
|
||||
default:
|
||||
return "Kapelle"
|
||||
}
|
||||
}
|
||||
|
||||
type Church struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ShortName string `json:"shortName"`
|
||||
Symbol ChurchSymbol `json:"symbol"`
|
||||
ColorHex string `json:"colorHex"`
|
||||
Address string `json:"address"`
|
||||
SortIndex int `json:"sortIndex"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
type Person struct {
|
||||
ID string `json:"id"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Roles []Role `json:"roles"`
|
||||
Email string `json:"email"`
|
||||
Phone string `json:"phone"`
|
||||
PreferredChurchIDs []string `json:"preferredChurchIDs"`
|
||||
PreferredWeekdays []int `json:"preferredWeekdays"`
|
||||
PreferredServiceTitles []string `json:"preferredServiceTitles"`
|
||||
MaxPerMonth int `json:"maxPerMonth"`
|
||||
Active bool `json:"active"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
func (p Person) FullName() string {
|
||||
return strings.TrimSpace(p.FirstName + " " + p.LastName)
|
||||
}
|
||||
|
||||
func (p Person) Initials() string {
|
||||
f := ""
|
||||
l := ""
|
||||
if r := []rune(p.FirstName); len(r) > 0 {
|
||||
f = string(r[0])
|
||||
}
|
||||
if r := []rune(p.LastName); len(r) > 0 {
|
||||
l = string(r[0])
|
||||
}
|
||||
return strings.ToUpper(f + l)
|
||||
}
|
||||
|
||||
func (p Person) AbbreviatedName() string {
|
||||
if r := []rune(p.FirstName); len(r) > 0 {
|
||||
return string(r[0]) + ". " + p.LastName
|
||||
}
|
||||
return p.LastName
|
||||
}
|
||||
|
||||
func (p Person) RoleLabel() string {
|
||||
var parts []string
|
||||
for _, role := range AllRoles {
|
||||
if p.CanFill(role) {
|
||||
parts = append(parts, role.Title())
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, " · ")
|
||||
}
|
||||
|
||||
func (p Person) CanFill(role Role) bool {
|
||||
for _, r := range p.Roles {
|
||||
if r == role {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p Person) HasRole(role Role) bool { return p.CanFill(role) }
|
||||
|
||||
func (p Person) HasPreference() bool {
|
||||
return len(p.PreferredChurchIDs) > 0 || len(p.PreferredWeekdays) > 0 || len(p.PreferredServiceTitles) > 0
|
||||
}
|
||||
|
||||
func IntContains(values []int, needle int) bool {
|
||||
for _, v := range values {
|
||||
if v == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func StringContains(values []string, needle string) bool {
|
||||
for _, v := range values {
|
||||
if v == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func UniqueStrings(values []string) []string {
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, v := range values {
|
||||
if !seen[v] {
|
||||
seen[v] = true
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type Absence struct {
|
||||
ID string `json:"id"`
|
||||
PersonID string `json:"personID"`
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
func (a Absence) Range() DayRange { return NewDayRange(a.Start, a.End) }
|
||||
func (a Absence) Overlaps(t time.Time) bool {
|
||||
return Normalize(t).Compare(Normalize(a.Start)) >= 0 && Normalize(t).Compare(Normalize(a.End)) <= 0
|
||||
}
|
||||
|
||||
func (a Absence) Label() string {
|
||||
start := MediumString(a.Start)
|
||||
end := MediumString(a.End)
|
||||
base := start
|
||||
if start != end {
|
||||
base = start + " – " + end
|
||||
}
|
||||
if a.Reason == "" {
|
||||
return base
|
||||
}
|
||||
return base + " · " + a.Reason
|
||||
}
|
||||
|
||||
type ServiceTemplate struct {
|
||||
ID string `json:"id"`
|
||||
ChurchID string `json:"churchID"`
|
||||
Weekday int `json:"weekday"`
|
||||
TimeMinutes int `json:"timeMinutes"`
|
||||
Title string `json:"title"`
|
||||
LectorsNeeded int `json:"lectorsNeeded"`
|
||||
HelpersNeeded int `json:"helpersNeeded"`
|
||||
ValidFrom time.Time `json:"validFrom"`
|
||||
ValidTo *time.Time `json:"validTo"`
|
||||
Active bool `json:"active"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
func (t ServiceTemplate) TimeLabel() string { return TimeString(t.TimeMinutes) }
|
||||
|
||||
func (t ServiceTemplate) WeekdayLabel() string {
|
||||
if t.Weekday >= 1 && t.Weekday <= 7 {
|
||||
return weekdayNames[t.Weekday]
|
||||
}
|
||||
return "?"
|
||||
}
|
||||
|
||||
func (t ServiceTemplate) RequirementLabel() string {
|
||||
var parts []string
|
||||
if t.LectorsNeeded > 0 {
|
||||
parts = append(parts, pluralCount(t.LectorsNeeded, "Lektor", "Lektoren"))
|
||||
}
|
||||
if t.HelpersNeeded > 0 {
|
||||
parts = append(parts, pluralCount(t.HelpersNeeded, "Kommunionhelfer", "Kommunionhelfer"))
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "Keine Dienste"
|
||||
}
|
||||
return strings.Join(parts, " · ")
|
||||
}
|
||||
|
||||
func pluralCount(n int, singular, plural string) string {
|
||||
if n == 1 {
|
||||
return "1× " + singular
|
||||
}
|
||||
return fmt.Sprintf("%d× %s", n, plural)
|
||||
}
|
||||
|
||||
func (t ServiceTemplate) IsValid(on time.Time) bool {
|
||||
if !t.Active {
|
||||
return false
|
||||
}
|
||||
day := Normalize(on)
|
||||
if Weekday(day) != t.Weekday {
|
||||
return false
|
||||
}
|
||||
if day.Before(Normalize(t.ValidFrom)) {
|
||||
return false
|
||||
}
|
||||
if t.ValidTo != nil && day.After(Normalize(*t.ValidTo)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type ServiceException struct {
|
||||
ID string `json:"id"`
|
||||
TemplateID string `json:"templateID"`
|
||||
Date time.Time `json:"date"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type ServiceKind string
|
||||
|
||||
const (
|
||||
KindRegular ServiceKind = "regular"
|
||||
KindSpecial ServiceKind = "special"
|
||||
)
|
||||
|
||||
func (k ServiceKind) Title() string {
|
||||
if k == KindSpecial {
|
||||
return "Sondergottesdienst"
|
||||
}
|
||||
return "Regulär"
|
||||
}
|
||||
|
||||
type ServiceOccurrence struct {
|
||||
ID string `json:"id"`
|
||||
ChurchID string `json:"churchID"`
|
||||
Location *string `json:"location"`
|
||||
TemplateID *string `json:"templateID"`
|
||||
Date time.Time `json:"date"`
|
||||
TimeMinutes int `json:"timeMinutes"`
|
||||
Title string `json:"title"`
|
||||
LectorsNeeded int `json:"lectorsNeeded"`
|
||||
HelpersNeeded int `json:"helpersNeeded"`
|
||||
Kind ServiceKind `json:"kind"`
|
||||
Notes string `json:"notes"`
|
||||
Locked bool `json:"locked"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
func (s ServiceOccurrence) PlaceName(church Church) string {
|
||||
if s.Location != nil && strings.TrimSpace(*s.Location) != "" {
|
||||
return *s.Location
|
||||
}
|
||||
return church.Name
|
||||
}
|
||||
|
||||
func (s ServiceOccurrence) TimeLabel() string { return TimeString(s.TimeMinutes) }
|
||||
func (s ServiceOccurrence) DateKey() string { return Key(s.Date) }
|
||||
func (s ServiceOccurrence) RequiredSlots() int {
|
||||
return s.LectorsNeeded + s.HelpersNeeded
|
||||
}
|
||||
func (s ServiceOccurrence) RequiredCount(role Role) int {
|
||||
if role == RoleHelper {
|
||||
return s.HelpersNeeded
|
||||
}
|
||||
return s.LectorsNeeded
|
||||
}
|
||||
func (s ServiceOccurrence) RolesNeeded() []Role {
|
||||
var roles []Role
|
||||
if s.LectorsNeeded > 0 {
|
||||
roles = append(roles, RoleLector)
|
||||
}
|
||||
if s.HelpersNeeded > 0 {
|
||||
roles = append(roles, RoleHelper)
|
||||
}
|
||||
return roles
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
// Liturgical model ---------------------------------------------------------
|
||||
|
||||
type LiturgicalRank string
|
||||
|
||||
const (
|
||||
RankWeekday LiturgicalRank = ""
|
||||
RankMemorial LiturgicalRank = "g"
|
||||
RankObligatoryMemorial LiturgicalRank = "G"
|
||||
RankFeast LiturgicalRank = "F"
|
||||
RankSolemnity LiturgicalRank = "H"
|
||||
)
|
||||
|
||||
func (r LiturgicalRank) Label() string {
|
||||
switch r {
|
||||
case RankMemorial:
|
||||
return "Gedenktag"
|
||||
case RankObligatoryMemorial:
|
||||
return "Gebotener Gedenktag"
|
||||
case RankFeast:
|
||||
return "Fest"
|
||||
case RankSolemnity:
|
||||
return "Hochfest"
|
||||
default:
|
||||
return "Wochentag"
|
||||
}
|
||||
}
|
||||
|
||||
func (r LiturgicalRank) ShortLabel() string { return string(r) }
|
||||
func (r LiturgicalRank) Priority() int {
|
||||
switch r {
|
||||
case RankMemorial:
|
||||
return 1
|
||||
case RankObligatoryMemorial:
|
||||
return 2
|
||||
case RankFeast:
|
||||
return 3
|
||||
case RankSolemnity:
|
||||
return 4
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
func (r LiturgicalRank) IsFeast() bool { return r == RankFeast || r == RankSolemnity }
|
||||
|
||||
type LiturgicalColor string
|
||||
|
||||
const (
|
||||
ColorWhite LiturgicalColor = "w"
|
||||
ColorRed LiturgicalColor = "r"
|
||||
ColorGreen LiturgicalColor = "g"
|
||||
ColorViolet LiturgicalColor = "v"
|
||||
ColorRose LiturgicalColor = "ros"
|
||||
ColorBlack LiturgicalColor = "s"
|
||||
ColorGold LiturgicalColor = "gold"
|
||||
)
|
||||
|
||||
func (c LiturgicalColor) Label() string {
|
||||
switch c {
|
||||
case ColorRed:
|
||||
return "Rot"
|
||||
case ColorGreen:
|
||||
return "Grün"
|
||||
case ColorViolet:
|
||||
return "Violett"
|
||||
case ColorRose:
|
||||
return "Rosa"
|
||||
case ColorBlack:
|
||||
return "Schwarz"
|
||||
case ColorGold:
|
||||
return "Gold"
|
||||
default:
|
||||
return "Weiß"
|
||||
}
|
||||
}
|
||||
|
||||
func LiturgicalColorFromAPI(value string) LiturgicalColor {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "r":
|
||||
return ColorRed
|
||||
case "g":
|
||||
return ColorGreen
|
||||
case "v":
|
||||
return ColorViolet
|
||||
case "ros", "rose":
|
||||
return ColorRose
|
||||
case "s", "sw":
|
||||
return ColorBlack
|
||||
case "gold":
|
||||
return ColorGold
|
||||
default:
|
||||
return ColorWhite
|
||||
}
|
||||
}
|
||||
|
||||
func LiturgicalColorHex(c LiturgicalColor) string {
|
||||
switch c {
|
||||
case ColorRed:
|
||||
return "#A5453F"
|
||||
case ColorGreen:
|
||||
return "#4F7D5A"
|
||||
case ColorViolet:
|
||||
return "#6E4B8E"
|
||||
case ColorRose:
|
||||
return "#C07A8B"
|
||||
case ColorBlack:
|
||||
return "#4A4440"
|
||||
default:
|
||||
return "#C2A14D"
|
||||
}
|
||||
}
|
||||
|
||||
type LiturgicalSeason string
|
||||
|
||||
const (
|
||||
SeasonAdvent LiturgicalSeason = "advent"
|
||||
SeasonChristmas LiturgicalSeason = "christmas"
|
||||
SeasonOrdinary LiturgicalSeason = "ordinary"
|
||||
SeasonLent LiturgicalSeason = "lent"
|
||||
SeasonEaster LiturgicalSeason = "easter"
|
||||
)
|
||||
|
||||
func (s LiturgicalSeason) Title() string {
|
||||
switch s {
|
||||
case SeasonAdvent:
|
||||
return "Advent"
|
||||
case SeasonChristmas:
|
||||
return "Weihnachtszeit"
|
||||
case SeasonLent:
|
||||
return "Österliche Bußzeit"
|
||||
case SeasonEaster:
|
||||
return "Osterzeit"
|
||||
default:
|
||||
return "Jahreskreis"
|
||||
}
|
||||
}
|
||||
|
||||
func (s LiturgicalSeason) ShortTitle() string {
|
||||
switch s {
|
||||
case SeasonAdvent:
|
||||
return "Advent"
|
||||
case SeasonChristmas:
|
||||
return "Weihnachten"
|
||||
case SeasonLent:
|
||||
return "Fastenzeit"
|
||||
case SeasonEaster:
|
||||
return "Osterzeit"
|
||||
default:
|
||||
return "Jahreskreis"
|
||||
}
|
||||
}
|
||||
|
||||
func (s LiturgicalSeason) ColorHex() string {
|
||||
switch s {
|
||||
case SeasonAdvent:
|
||||
return "#6E4B8E"
|
||||
case SeasonChristmas:
|
||||
return "#B58A3B"
|
||||
case SeasonLent:
|
||||
return "#75516F"
|
||||
case SeasonEaster:
|
||||
return "#C9A227"
|
||||
default:
|
||||
return "#4F7D5A"
|
||||
}
|
||||
}
|
||||
|
||||
type FeastSymbol string
|
||||
|
||||
const (
|
||||
FeastCross FeastSymbol = "cross"
|
||||
FeastStar FeastSymbol = "star"
|
||||
FeastFlame FeastSymbol = "flame"
|
||||
FeastSun FeastSymbol = "sun"
|
||||
FeastLily FeastSymbol = "lily"
|
||||
FeastCrown FeastSymbol = "crown"
|
||||
FeastHeart FeastSymbol = "heart"
|
||||
FeastBook FeastSymbol = "book"
|
||||
FeastCandle FeastSymbol = "candle"
|
||||
FeastDove FeastSymbol = "dove"
|
||||
)
|
||||
|
||||
func (f FeastSymbol) Label() string {
|
||||
switch f {
|
||||
case FeastCross:
|
||||
return "Kreuz"
|
||||
case FeastStar:
|
||||
return "Stern"
|
||||
case FeastFlame:
|
||||
return "Feuer"
|
||||
case FeastSun:
|
||||
return "Sonne"
|
||||
case FeastLily:
|
||||
return "Lilie"
|
||||
case FeastCrown:
|
||||
return "Krone"
|
||||
case FeastHeart:
|
||||
return "Herz"
|
||||
case FeastBook:
|
||||
return "Buch"
|
||||
case FeastCandle:
|
||||
return "Licht"
|
||||
case FeastDove:
|
||||
return "Taube"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
type Readings struct {
|
||||
First string `json:"first"`
|
||||
Psalm string `json:"psalm"`
|
||||
Second string `json:"second"`
|
||||
Gospel string `json:"gospel"`
|
||||
}
|
||||
|
||||
func (r Readings) IsEmpty() bool {
|
||||
return r.First == "" && r.Psalm == "" && r.Second == "" && r.Gospel == ""
|
||||
}
|
||||
|
||||
func (r Readings) ShortLabel() string {
|
||||
var parts []string
|
||||
if r.First != "" {
|
||||
parts = append(parts, r.First)
|
||||
}
|
||||
if r.Second != "" {
|
||||
parts = append(parts, r.Second)
|
||||
}
|
||||
if r.Gospel != "" {
|
||||
parts = append(parts, r.Gospel)
|
||||
}
|
||||
return strings.Join(parts, " · ")
|
||||
}
|
||||
|
||||
func (r Readings) FullLabel() string {
|
||||
var lines []string
|
||||
if r.First != "" {
|
||||
lines = append(lines, "1. Lesung: "+r.First)
|
||||
}
|
||||
if r.Psalm != "" {
|
||||
lines = append(lines, "Psalm: "+r.Psalm)
|
||||
}
|
||||
if r.Second != "" {
|
||||
lines = append(lines, "2. Lesung: "+r.Second)
|
||||
}
|
||||
if r.Gospel != "" {
|
||||
lines = append(lines, "Evangelium: "+r.Gospel)
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
type LiturgicalDay struct {
|
||||
Date time.Time `json:"date"`
|
||||
Title string `json:"title"`
|
||||
Rank LiturgicalRank `json:"rank"`
|
||||
Color LiturgicalColor `json:"color"`
|
||||
Remark string `json:"remark"`
|
||||
Readings Readings `json:"readings"`
|
||||
IsObligation bool `json:"isObligation"`
|
||||
Source string `json:"source"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
func (d LiturgicalDay) DateKey() string { return Key(d.Date) }
|
||||
func (d LiturgicalDay) IsSunday() bool { return IsSunday(d.Date) }
|
||||
func (d LiturgicalDay) IsHighFeast() bool {
|
||||
return d.Rank == RankSolemnity || strings.Contains(strings.ToLower(d.Title), "hochfest")
|
||||
}
|
||||
func (d LiturgicalDay) IsFeast() bool { return d.Rank.IsFeast() || d.IsHighFeast() }
|
||||
func (d LiturgicalDay) Season() LiturgicalSeason {
|
||||
return SeasonFor(d.Date)
|
||||
}
|
||||
func (d LiturgicalDay) Symbol() FeastSymbol {
|
||||
return SymbolFor(d.Title, d.Rank, d.Date)
|
||||
}
|
||||
func (d LiturgicalDay) DisplayTitle() string {
|
||||
if d.Title == "" {
|
||||
if d.IsSunday() {
|
||||
return "Sonntag"
|
||||
}
|
||||
return LongString(d.Date)
|
||||
}
|
||||
return d.Title
|
||||
}
|
||||
func (d LiturgicalDay) BadgeText() string {
|
||||
if d.IsSunday() && d.IsObligation {
|
||||
return "Sonntag"
|
||||
}
|
||||
if d.Rank != RankWeekday {
|
||||
return d.Rank.Label()
|
||||
}
|
||||
if d.IsObligation {
|
||||
return "Gebotener Feiertag"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d LiturgicalDay) ColorHex() string { return LiturgicalColorHex(d.Color) }
|
||||
|
||||
// View support -------------------------------------------------------------
|
||||
|
||||
type ServiceWithAssignments struct {
|
||||
Service ServiceOccurrence
|
||||
Church Church
|
||||
Assignments []Assignment
|
||||
}
|
||||
|
||||
func (s ServiceWithAssignments) AssignmentsFor(role Role) []Assignment {
|
||||
var out []Assignment
|
||||
for _, a := range s.Assignments {
|
||||
if a.Role == role {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s ServiceWithAssignments) OpenSlotsFor(role Role) int {
|
||||
open := s.Service.RequiredCount(role) - len(s.AssignmentsFor(role))
|
||||
if open < 0 {
|
||||
return 0
|
||||
}
|
||||
return open
|
||||
}
|
||||
|
||||
func (s ServiceWithAssignments) FilledSlots() int { return len(s.Assignments) }
|
||||
func (s ServiceWithAssignments) OpenSlots() int {
|
||||
open := s.Service.RequiredSlots() - len(s.Assignments)
|
||||
if open < 0 {
|
||||
return 0
|
||||
}
|
||||
return open
|
||||
}
|
||||
func (s ServiceWithAssignments) IsFullyStaffed() bool { return s.OpenSlots() == 0 }
|
||||
|
||||
type DayPlanRow struct {
|
||||
Date time.Time
|
||||
LiturgicalDay *LiturgicalDay
|
||||
Services []ServiceWithAssignments
|
||||
}
|
||||
|
||||
func (r DayPlanRow) DateKey() string { return Key(r.Date) }
|
||||
func (r DayPlanRow) OpenSlots() int {
|
||||
total := 0
|
||||
for _, s := range r.Services {
|
||||
total += s.OpenSlots()
|
||||
}
|
||||
return total
|
||||
}
|
||||
func (r DayPlanRow) AssignmentCount() int {
|
||||
total := 0
|
||||
for _, s := range r.Services {
|
||||
total += len(s.Assignments)
|
||||
}
|
||||
return total
|
||||
}
|
||||
func (r DayPlanRow) HasServices() bool { return len(r.Services) > 0 }
|
||||
|
||||
func (r DayPlanRow) IsSunday() bool {
|
||||
return (r.LiturgicalDay != nil && r.LiturgicalDay.IsSunday()) || IsSunday(r.Date)
|
||||
}
|
||||
func (r DayPlanRow) IsHighFeast() bool {
|
||||
return r.LiturgicalDay != nil && r.LiturgicalDay.IsHighFeast()
|
||||
}
|
||||
func (r DayPlanRow) IsFeast() bool {
|
||||
return r.LiturgicalDay != nil && r.LiturgicalDay.IsFeast()
|
||||
}
|
||||
func (r DayPlanRow) IsSpecialDay() bool {
|
||||
if r.IsSunday() || r.IsFeast() {
|
||||
return true
|
||||
}
|
||||
return r.LiturgicalDay != nil && r.LiturgicalDay.IsObligation
|
||||
}
|
||||
func (r DayPlanRow) IsObligation() bool {
|
||||
return r.LiturgicalDay != nil && r.LiturgicalDay.IsObligation
|
||||
}
|
||||
|
||||
func (r DayPlanRow) ServicesForChurch(churchID string) []ServiceWithAssignments {
|
||||
var out []ServiceWithAssignments
|
||||
for _, s := range r.Services {
|
||||
if s.Church.ID == churchID {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type UnfilledSlot struct {
|
||||
Service ServiceOccurrence
|
||||
ChurchName string
|
||||
Role Role
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (u UnfilledSlot) ID() string { return u.Service.ID + "-" + string(u.Role) }
|
||||
|
||||
type PersonStat struct {
|
||||
Person Person
|
||||
Total int
|
||||
Lectors int
|
||||
Helpers int
|
||||
ChurchCounts map[string]int
|
||||
PreferredHits int
|
||||
SundayCount int
|
||||
LastAssignment *time.Time
|
||||
}
|
||||
|
||||
func (s PersonStat) PreferenceRate() float64 {
|
||||
if s.Total == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(s.PreferredHits) / float64(s.Total)
|
||||
}
|
||||
|
||||
type ChurchStat struct {
|
||||
Church Church
|
||||
Assignments int
|
||||
Services int
|
||||
OpenSlots int
|
||||
PersonCount int
|
||||
}
|
||||
|
||||
type RangeStatistics struct {
|
||||
Range DayRange
|
||||
ServiceCount int
|
||||
AssignmentCount int
|
||||
OpenSlots int
|
||||
RequiredSlots int
|
||||
PersonStats []PersonStat
|
||||
ChurchStats []ChurchStat
|
||||
MonthlyCounts map[string]int
|
||||
SundayServiceCount int
|
||||
SundayFilled int
|
||||
PreferenceHits int
|
||||
PreferenceEligible int
|
||||
AbsenceDays int
|
||||
}
|
||||
|
||||
func (s RangeStatistics) CoverageRate() float64 {
|
||||
if s.RequiredSlots == 0 {
|
||||
return 1
|
||||
}
|
||||
return float64(s.AssignmentCount) / float64(s.RequiredSlots)
|
||||
}
|
||||
|
||||
func (s RangeStatistics) PreferenceRate() float64 {
|
||||
if s.PreferenceEligible == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(s.PreferenceHits) / float64(s.PreferenceEligible)
|
||||
}
|
||||
|
||||
func (s RangeStatistics) ActivePeople() int {
|
||||
n := 0
|
||||
for _, p := range s.PersonStats {
|
||||
if p.Total > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (s RangeStatistics) AverageAssignments() float64 {
|
||||
count, total := 0, 0
|
||||
for _, p := range s.PersonStats {
|
||||
if p.Total > 0 {
|
||||
count++
|
||||
total += p.Total
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(total) / float64(count)
|
||||
}
|
||||
|
||||
type PlannerOptions struct {
|
||||
ReplaceExisting bool
|
||||
RespectPreferredWeekdays bool
|
||||
AllowDoubleRolesOnSameDay bool
|
||||
WeightChurchPreference float64
|
||||
WeightServicePreference float64
|
||||
WeightFairness float64
|
||||
WeightDualRolePreference float64
|
||||
MaxAssignmentsPerDay int
|
||||
}
|
||||
|
||||
func DefaultPlannerOptions() PlannerOptions {
|
||||
return PlannerOptions{
|
||||
RespectPreferredWeekdays: true,
|
||||
WeightChurchPreference: 8,
|
||||
WeightServicePreference: 4,
|
||||
WeightFairness: 2.2,
|
||||
WeightDualRolePreference: 14,
|
||||
MaxAssignmentsPerDay: 1,
|
||||
}
|
||||
}
|
||||
|
||||
type PlanResult struct {
|
||||
Assignments []Assignment
|
||||
Unfilled []UnfilledSlot
|
||||
FilledCount int
|
||||
Message string
|
||||
}
|
||||
|
||||
type CandidateSuggestion struct {
|
||||
Person Person
|
||||
Score float64
|
||||
Warnings []string
|
||||
Blocked bool
|
||||
Preferred bool
|
||||
TotalAssignments int
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
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
|
||||
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
|
||||
}
|
||||
|
||||
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++ {
|
||||
result := p.bestCandidate(service, role, activePeople, absencesByPerson,
|
||||
totalByPerson, monthByPerson, dayServicesByPerson, churchByPerson,
|
||||
lastDateByPerson, assignedRoles)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
) 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 && len(person.PreferredWeekdays) > 0 &&
|
||||
!IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
|
||||
blockedReasons["Einsatztag passt nicht"]++
|
||||
continue
|
||||
}
|
||||
month := MonthKey(service.Date)
|
||||
usedThisMonth := monthByPerson[person.ID+"|"+month]
|
||||
if 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 IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
|
||||
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,
|
||||
ignorePreferredWeekdays bool,
|
||||
) []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)
|
||||
|
||||
var suggestions []CandidateSuggestion
|
||||
for _, person := range eligible {
|
||||
var warnings []string
|
||||
blocked := false
|
||||
for _, a := range absences {
|
||||
if a.PersonID == person.ID && a.Overlaps(service.Date) {
|
||||
warnings = append(warnings, "abwesend")
|
||||
blocked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ignorePreferredWeekdays && len(person.PreferredWeekdays) > 0 && !IntContains(person.PreferredWeekdays, weekday) {
|
||||
warnings = append(warnings, "Einsatztag passt nicht")
|
||||
blocked = true
|
||||
}
|
||||
if person.MaxPerMonth > 0 && monthlyCounts[person.ID+"|"+monthKey] >= person.MaxPerMonth {
|
||||
warnings = append(warnings, "Monatslimit")
|
||||
blocked = 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 IntContains(person.PreferredWeekdays, weekday) {
|
||||
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, 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
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type StatisticsCalculator struct{}
|
||||
|
||||
func ComputeStatistics(
|
||||
r DayRange,
|
||||
services []ServiceOccurrence,
|
||||
assignments []Assignment,
|
||||
people []Person,
|
||||
churches []Church,
|
||||
absences []Absence,
|
||||
) RangeStatistics {
|
||||
servicesByID := map[string]ServiceOccurrence{}
|
||||
for _, s := range services {
|
||||
servicesByID[s.ID] = s
|
||||
}
|
||||
peopleByID := map[string]Person{}
|
||||
for _, p := range people {
|
||||
peopleByID[p.ID] = p
|
||||
}
|
||||
assignmentsByPerson := map[string][]Assignment{}
|
||||
for _, a := range assignments {
|
||||
assignmentsByPerson[a.PersonID] = append(assignmentsByPerson[a.PersonID], a)
|
||||
}
|
||||
assignmentsByService := map[string][]Assignment{}
|
||||
for _, a := range assignments {
|
||||
assignmentsByService[a.ServiceID] = append(assignmentsByService[a.ServiceID], a)
|
||||
}
|
||||
|
||||
personStats := make([]PersonStat, 0, len(people))
|
||||
for _, person := range people {
|
||||
own := assignmentsByPerson[person.ID]
|
||||
lectors, helpers := 0, 0
|
||||
churchCounts := map[string]int{}
|
||||
preferredHits, sundays := 0, 0
|
||||
var lastDate *time.Time
|
||||
for _, a := range own {
|
||||
service, ok := servicesByID[a.ServiceID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if a.Role == RoleLector {
|
||||
lectors++
|
||||
} else {
|
||||
helpers++
|
||||
}
|
||||
churchCounts[service.ChurchID]++
|
||||
if IsSunday(service.Date) {
|
||||
sundays++
|
||||
}
|
||||
if lastDate == nil || service.Date.After(*lastDate) {
|
||||
d := service.Date
|
||||
lastDate = &d
|
||||
}
|
||||
if PreferenceHit(person, service) {
|
||||
preferredHits++
|
||||
}
|
||||
}
|
||||
stat := PersonStat{
|
||||
Person: person, Total: len(own), Lectors: lectors, Helpers: helpers,
|
||||
ChurchCounts: churchCounts, PreferredHits: preferredHits, SundayCount: sundays,
|
||||
}
|
||||
if lastDate != nil {
|
||||
stat.LastAssignment = lastDate
|
||||
}
|
||||
personStats = append(personStats, stat)
|
||||
}
|
||||
sort.SliceStable(personStats, func(i, j int) bool {
|
||||
if personStats[i].Total != personStats[j].Total {
|
||||
return personStats[i].Total > personStats[j].Total
|
||||
}
|
||||
return personStats[i].Person.LastName < personStats[j].Person.LastName
|
||||
})
|
||||
|
||||
churchStats := make([]ChurchStat, 0, len(churches))
|
||||
for _, church := range churches {
|
||||
var churchServices []ServiceOccurrence
|
||||
serviceIDs := map[string]bool{}
|
||||
for _, s := range services {
|
||||
if s.ChurchID == church.ID {
|
||||
churchServices = append(churchServices, s)
|
||||
serviceIDs[s.ID] = true
|
||||
}
|
||||
}
|
||||
churchAssignments := 0
|
||||
personIDs := map[string]bool{}
|
||||
for _, a := range assignments {
|
||||
if serviceIDs[a.ServiceID] {
|
||||
churchAssignments++
|
||||
personIDs[a.PersonID] = true
|
||||
}
|
||||
}
|
||||
open := 0
|
||||
for _, s := range churchServices {
|
||||
remaining := s.RequiredSlots() - len(assignmentsByService[s.ID])
|
||||
if remaining > 0 {
|
||||
open += remaining
|
||||
}
|
||||
}
|
||||
churchStats = append(churchStats, ChurchStat{
|
||||
Church: church, Assignments: churchAssignments, Services: len(churchServices),
|
||||
OpenSlots: open, PersonCount: len(personIDs),
|
||||
})
|
||||
}
|
||||
sort.SliceStable(churchStats, func(i, j int) bool {
|
||||
return churchStats[i].Church.SortIndex < churchStats[j].Church.SortIndex
|
||||
})
|
||||
|
||||
monthly := map[string]int{}
|
||||
for _, a := range assignments {
|
||||
s, ok := servicesByID[a.ServiceID]
|
||||
if ok {
|
||||
monthly[MonthKey(s.Date)]++
|
||||
}
|
||||
}
|
||||
|
||||
sundayServiceCount := 0
|
||||
sundayIDs := map[string]bool{}
|
||||
for _, s := range services {
|
||||
if IsSunday(s.Date) {
|
||||
sundayServiceCount++
|
||||
sundayIDs[s.ID] = true
|
||||
}
|
||||
}
|
||||
sundayFilled := 0
|
||||
for _, a := range assignments {
|
||||
if sundayIDs[a.ServiceID] {
|
||||
sundayFilled++
|
||||
}
|
||||
}
|
||||
requiredSlots := 0
|
||||
for _, s := range services {
|
||||
requiredSlots += s.RequiredSlots()
|
||||
}
|
||||
openSlots := requiredSlots - len(assignments)
|
||||
if openSlots < 0 {
|
||||
openSlots = 0
|
||||
}
|
||||
|
||||
preferenceHits, preferenceEligible := 0, 0
|
||||
for _, a := range assignments {
|
||||
s, ok := servicesByID[a.ServiceID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
person, ok := peopleByID[a.PersonID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if person.HasPreference() {
|
||||
preferenceEligible++
|
||||
if PreferenceHit(person, s) {
|
||||
preferenceHits++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
active := map[string]bool{}
|
||||
for _, p := range people {
|
||||
if p.Active {
|
||||
active[p.ID] = true
|
||||
}
|
||||
}
|
||||
absenceDays := 0
|
||||
for _, a := range absences {
|
||||
if !active[a.PersonID] {
|
||||
continue
|
||||
}
|
||||
clamped := a.Range().Clamped(r)
|
||||
if !clamped.Start.After(clamped.End) {
|
||||
absenceDays += clamped.DayCount()
|
||||
}
|
||||
}
|
||||
|
||||
return RangeStatistics{
|
||||
Range: r, ServiceCount: len(services), AssignmentCount: len(assignments),
|
||||
OpenSlots: openSlots, RequiredSlots: requiredSlots, PersonStats: personStats,
|
||||
ChurchStats: churchStats, MonthlyCounts: monthly, SundayServiceCount: sundayServiceCount,
|
||||
SundayFilled: sundayFilled, PreferenceHits: preferenceHits,
|
||||
PreferenceEligible: preferenceEligible, AbsenceDays: absenceDays,
|
||||
}
|
||||
}
|
||||
|
||||
func PreferenceHit(person Person, service ServiceOccurrence) bool {
|
||||
if StringContains(person.PreferredChurchIDs, service.ChurchID) {
|
||||
return true
|
||||
}
|
||||
if IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
|
||||
return true
|
||||
}
|
||||
title := strings.ToLower(service.Title)
|
||||
for _, preference := range person.PreferredServiceTitles {
|
||||
if preference != "" && strings.Contains(title, strings.ToLower(preference)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
)
|
||||
|
||||
// NewID returns a random RFC-4122 version 4 UUID string.
|
||||
func NewID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return time.Now().Format("20060102150405.000000000")
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
buf := make([]byte, 36)
|
||||
hex.Encode(buf[0:8], b[0:4])
|
||||
buf[8] = '-'
|
||||
hex.Encode(buf[9:13], b[4:6])
|
||||
buf[13] = '-'
|
||||
hex.Encode(buf[14:18], b[6:8])
|
||||
buf[18] = '-'
|
||||
hex.Encode(buf[19:23], b[8:10])
|
||||
buf[23] = '-'
|
||||
hex.Encode(buf[24:36], b[10:16])
|
||||
return string(buf)
|
||||
}
|
||||
|
||||
func newID() string { return NewID() }
|
||||
|
||||
func now() time.Time { return Normalize(time.Now()) }
|
||||
Reference in new issue
Block a user