Files
LektorenPlan/Sources/LektorenPlanCore/Models.swift
T

1106 lines
35 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
// MARK: - Roles
public enum Role: String, Codable, CaseIterable, Identifiable, Sendable, Hashable {
case lector
case helper
public var id: String { rawValue }
public var title: String {
switch self {
case .lector: "Lektor"
case .helper: "Kommunionhelfer"
}
}
public var plural: String {
switch self {
case .lector: "Lektoren"
case .helper: "Kommunionhelfer"
}
}
public var shortCode: String {
switch self {
case .lector: "L"
case .helper: "K"
}
}
public var symbolName: String {
switch self {
case .lector: "book.closed.fill"
case .helper: "hand.raised.fill"
}
}
/// The other role a service may need. Lector and communion helper do not
/// exclude each other, so one person can fill both at the same service.
public var complementary: Role {
switch self {
case .lector: .helper
case .helper: .lector
}
}
}
// MARK: - Church
public enum ChurchSymbol: String, Codable, CaseIterable, Sendable {
case basilica
case gothic
case modern
case rotunda
case roundTower
case chapel
public var caption: String {
switch self {
case .basilica: "Romanische Basilika"
case .gothic: "Neugotische Kirche"
case .modern: "Moderner Kirchenbau"
case .rotunda: "Rundkirche"
case .roundTower: "Rundturm"
case .chapel: "Kapelle"
}
}
}
public struct Church: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var name: String
public var shortName: String
public var symbol: ChurchSymbol
public var colorHex: String
public var address: String
public var sortIndex: Int
public var notes: String
public init(
id: String = UUID().uuidString,
name: String,
shortName: String,
symbol: ChurchSymbol,
colorHex: String,
address: String = "",
sortIndex: Int = 0,
notes: String = ""
) {
self.id = id
self.name = name
self.shortName = shortName
self.symbol = symbol
self.colorHex = colorHex
self.address = address
self.sortIndex = sortIndex
self.notes = notes
}
/// Stable demo identifiers so exported plans remain readable.
public static let andreasID = "church-andreas"
public static let evergislusID = "church-evergislus"
public static let herzJesuID = "church-herz-jesu"
public static let hildegardID = "church-hildegard"
}
// MARK: - People
public enum WeekdayPeriod: String, Codable, CaseIterable, Identifiable, Sendable, Hashable {
case all
case morning
case afternoon
case evening
public var id: String { rawValue }
public var label: String {
switch self {
case .morning: "vormittags (0–12 Uhr)"
case .afternoon: "nachmittags (12–17 Uhr)"
case .evening: "abends (ab 17 Uhr)"
case .all: "ganztägig"
}
}
public var shortLabel: String {
switch self {
case .morning: "vormittags"
case .afternoon: "nachmittags"
case .evening: "abends"
case .all: "ganztägig"
}
}
/// Morning is 0–12, afternoon 12–17, evening after 17.
public func matches(timeMinutes: Int) -> Bool {
switch self {
case .morning: timeMinutes < 12 * 60
case .afternoon: timeMinutes >= 12 * 60 && timeMinutes < 17 * 60
case .evening: timeMinutes >= 17 * 60
case .all: true
}
}
}
public struct WeekdayPeriodPreference: Codable, Hashable, Sendable, Identifiable {
public var weekday: Int
public var period: WeekdayPeriod
public var id: Int { weekday }
public init(weekday: Int, period: WeekdayPeriod = .all) {
self.weekday = weekday
self.period = period
}
}
public struct Person: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var shortCode: String
public var firstName: String
public var lastName: String
public var roles: Set<Role>
public var email: String
public var phone: String
public var preferredChurchIDs: Set<String>
public var preferredWeekdays: Set<Int> // 1 = Sunday … 7 = Saturday; empty = no preference
public var preferredWeekdayPeriods: [WeekdayPeriodPreference]
public var preferredServiceTitles: [String]
public var maxPerMonth: Int
public var allowBeyondPreferences: Bool
public var active: Bool
public var notes: String
public init(
id: String = UUID().uuidString,
shortCode: String = "",
firstName: String,
lastName: String,
roles: Set<Role> = [.lector],
email: String = "",
phone: String = "",
preferredChurchIDs: Set<String> = [],
preferredWeekdays: Set<Int> = [],
preferredWeekdayPeriods: [WeekdayPeriodPreference] = [],
preferredServiceTitles: [String] = [],
maxPerMonth: Int = 6,
allowBeyondPreferences: Bool = false,
active: Bool = true,
notes: String = ""
) {
self.id = id
self.shortCode = shortCode
self.firstName = firstName
self.lastName = lastName
self.roles = roles
self.email = email
self.phone = phone
self.preferredChurchIDs = preferredChurchIDs
self.preferredWeekdays = preferredWeekdays
self.preferredWeekdayPeriods = preferredWeekdayPeriods
self.preferredServiceTitles = preferredServiceTitles
self.maxPerMonth = maxPerMonth
self.allowBeyondPreferences = allowBeyondPreferences
self.active = active
self.notes = notes
}
private enum CodingKeys: String, CodingKey {
case id, shortCode, firstName, lastName, roles, email, phone
case preferredChurchIDs, preferredWeekdays, preferredWeekdayPeriods
case preferredServiceTitles, maxPerMonth, allowBeyondPreferences
case active, notes
}
/// Older exchange files and backups predate the Kürzel, weekday periods and
/// the beyond-preferences flag, so every new key falls back to a default.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? UUID().uuidString
shortCode = try container.decodeIfPresent(String.self, forKey: .shortCode) ?? ""
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
roles = try container.decodeIfPresent(Set<Role>.self, forKey: .roles) ?? [.lector]
email = try container.decodeIfPresent(String.self, forKey: .email) ?? ""
phone = try container.decodeIfPresent(String.self, forKey: .phone) ?? ""
preferredChurchIDs = try container.decodeIfPresent(Set<String>.self, forKey: .preferredChurchIDs) ?? []
preferredWeekdays = try container.decodeIfPresent(Set<Int>.self, forKey: .preferredWeekdays) ?? []
preferredWeekdayPeriods = try container.decodeIfPresent([WeekdayPeriodPreference].self, forKey: .preferredWeekdayPeriods) ?? []
preferredServiceTitles = try container.decodeIfPresent([String].self, forKey: .preferredServiceTitles) ?? []
maxPerMonth = try container.decodeIfPresent(Int.self, forKey: .maxPerMonth) ?? 6
allowBeyondPreferences = try container.decodeIfPresent(Bool.self, forKey: .allowBeyondPreferences) ?? false
active = try container.decodeIfPresent(Bool.self, forKey: .active) ?? true
notes = try container.decodeIfPresent(String.self, forKey: .notes) ?? ""
}
public var fullName: String {
"\(firstName) \(lastName)".trimmingCharacters(in: .whitespaces)
}
public var initials: String {
let f = firstName.first.map(String.init) ?? ""
let l = lastName.first.map(String.init) ?? ""
return (f + l).uppercased()
}
public var firstNameWithInitial: String {
guard let initial = lastName.first else { return firstName }
return "\(firstName) \(initial)."
}
/// Compact display for the calendar: surname in full, first name abbreviated.
public var abbreviatedName: String {
guard let initial = firstName.first else { return lastName }
return "\(initial). \(lastName)"
}
public var roleLabel: String {
let ordered = Role.allCases.filter { roles.contains($0) }
return ordered.map(\.title).joined(separator: " · ")
}
public func canFill(_ role: Role) -> Bool { roles.contains(role) }
/// Guest-facing label: an explicitly maintained Kürzel wins, otherwise the
/// initials from first and last name.
public var displayShort: String {
let code = shortCode.trimmingCharacters(in: .whitespacesAndNewlines)
return code.isEmpty ? initials : code
}
public func weekdayPeriod(for weekday: Int) -> WeekdayPeriod {
preferredWeekdayPeriods.first { $0.weekday == weekday }?.period ?? .all
}
/// High feasts count like Sundays, so a Sunday preference also covers them.
/// An empty weekday list means no restriction.
public func matchesWeekdayPreference(weekday: Int, timeMinutes: Int, highFeast: Bool) -> Bool {
guard !preferredWeekdays.isEmpty else { return true }
var candidates = [weekday]
if highFeast && weekday != 1 { candidates.append(1) }
for day in candidates where preferredWeekdays.contains(day) {
if weekdayPeriod(for: day).matches(timeMinutes: timeMinutes) { return true }
}
return false
}
/// Free-text planning note shown next to assignments and candidates.
public var preferenceNote: String {
notes.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
public struct Absence: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var personID: String
public var start: Date
public var end: Date
public var reason: String
public init(
id: String = UUID().uuidString,
personID: String,
start: Date,
end: Date,
reason: String = ""
) {
self.id = id
self.personID = personID
self.start = DayMath.normalize(start)
self.end = DayMath.normalize(end)
self.reason = reason
}
public var range: DayRange { DayRange(start: start, end: end) }
public func overlaps(_ day: Date) -> Bool {
range.contains(day)
}
public var label: String {
let start = DayMath.mediumString(start)
let end = DayMath.mediumString(end)
let base = start == end ? start : "\(start) – \(end)"
return reason.isEmpty ? base : "\(base) · \(reason)"
}
}
// MARK: - Service order
public struct ServiceTemplate: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var churchID: String
public var weekday: Int // 1 = Sunday … 7 = Saturday
public var timeMinutes: Int
public var title: String
public var lectorsNeeded: Int
public var helpersNeeded: Int
public var validFrom: Date
public var validTo: Date?
public var active: Bool
public var notes: String
public init(
id: String = UUID().uuidString,
churchID: String,
weekday: Int,
timeMinutes: Int,
title: String,
lectorsNeeded: Int = 1,
helpersNeeded: Int = 1,
validFrom: Date = DayMath.date(fromKey: "2025-01-01") ?? DayMath.today(),
validTo: Date? = nil,
active: Bool = true,
notes: String = ""
) {
self.id = id
self.churchID = churchID
self.weekday = weekday
self.timeMinutes = timeMinutes
self.title = title
self.lectorsNeeded = lectorsNeeded
self.helpersNeeded = helpersNeeded
self.validFrom = DayMath.normalize(validFrom)
self.validTo = validTo.map(DayMath.normalize)
self.active = active
self.notes = notes
}
public var timeLabel: String { DayMath.timeString(minutes: timeMinutes) }
public var weekdayLabel: String {
let names = ["", "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"]
return names.indices.contains(weekday) ? names[weekday] : "?"
}
public var requirementLabel: String {
var parts: [String] = []
if lectorsNeeded > 0 { parts.append("\(lectorsNeeded)× Lektor") }
if helpersNeeded > 0 { parts.append("\(helpersNeeded)× Kommunionhelfer") }
return parts.isEmpty ? "Keine Dienste" : parts.joined(separator: " · ")
}
public func isValid(on date: Date) -> Bool {
guard active else { return false }
let day = DayMath.normalize(date)
guard DayMath.weekday(day) == weekday else { return false }
guard day >= DayMath.normalize(validFrom) else { return false }
if let validTo, day > DayMath.normalize(validTo) { return false }
return true
}
}
public struct ServiceException: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var templateID: String
public var date: Date
public var reason: String
public init(id: String = UUID().uuidString, templateID: String, date: Date, reason: String = "") {
self.id = id
self.templateID = templateID
self.date = DayMath.normalize(date)
self.reason = reason
}
}
public enum ServiceKind: String, Codable, CaseIterable, Sendable {
case regular
case special
public var title: String {
switch self {
case .regular: "Regulär"
case .special: "Sondergottesdienst"
}
}
}
public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var churchID: String
/// Free-text location for special services (e.g. open-air worship).
/// `nil` means the service takes place in the assigned church.
public var location: String?
public var templateID: String?
public var date: Date
public var timeMinutes: Int
public var title: String
public var lectorsNeeded: Int
public var helpersNeeded: Int
public var kind: ServiceKind
public var notes: String
public var locked: Bool
public var createdAt: Date
public init(
id: String = UUID().uuidString,
churchID: String,
location: String? = nil,
templateID: String? = nil,
date: Date,
timeMinutes: Int,
title: String,
lectorsNeeded: Int = 1,
helpersNeeded: Int = 1,
kind: ServiceKind = .regular,
notes: String = "",
locked: Bool = false,
createdAt: Date = Date()
) {
self.id = id
self.churchID = churchID
let trimmedLocation = location?.trimmingCharacters(in: .whitespacesAndNewlines)
self.location = (trimmedLocation?.isEmpty ?? true) ? nil : trimmedLocation
self.templateID = templateID
self.date = DayMath.normalize(date)
self.timeMinutes = timeMinutes
self.title = title
self.lectorsNeeded = max(0, lectorsNeeded)
self.helpersNeeded = max(0, helpersNeeded)
self.kind = kind
self.notes = notes
self.locked = locked
self.createdAt = createdAt
}
public func placeName(church: Church) -> String {
location ?? church.name
}
public var timeLabel: String { DayMath.timeString(minutes: timeMinutes) }
public var dateKey: String { DayMath.key(date) }
public var requiredSlots: Int { lectorsNeeded + helpersNeeded }
public var rolesNeeded: [Role] {
var result: [Role] = []
if lectorsNeeded > 0 { result.append(.lector) }
if helpersNeeded > 0 { result.append(.helper) }
return result
}
public func requiredCount(for role: Role) -> Int {
switch role {
case .lector: lectorsNeeded
case .helper: helpersNeeded
}
}
}
public struct Assignment: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var serviceID: String
public var personID: String
public var role: Role
public var locked: Bool
public var beyondPreferences: Bool
public var note: String
public var createdAt: Date
public init(
id: String = UUID().uuidString,
serviceID: String,
personID: String,
role: Role,
locked: Bool = false,
beyondPreferences: Bool = false,
note: String = "",
createdAt: Date = Date()
) {
self.id = id
self.serviceID = serviceID
self.personID = personID
self.role = role
self.locked = locked
self.beyondPreferences = beyondPreferences
self.note = note
self.createdAt = createdAt
}
private enum CodingKeys: String, CodingKey {
case id, serviceID, personID, role, locked, beyondPreferences, note, createdAt
}
/// Exchange files created before the beyond-preferences marker decode to
/// the ordinary case.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? UUID().uuidString
serviceID = try container.decode(String.self, forKey: .serviceID)
personID = try container.decode(String.self, forKey: .personID)
role = try container.decode(Role.self, forKey: .role)
locked = try container.decodeIfPresent(Bool.self, forKey: .locked) ?? false
beyondPreferences = try container.decodeIfPresent(Bool.self, forKey: .beyondPreferences) ?? false
note = try container.decodeIfPresent(String.self, forKey: .note) ?? ""
createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? Date()
}
}
// MARK: - Liturgy
public enum LiturgicalRank: String, Codable, CaseIterable, Sendable, Comparable {
case weekday = ""
case memorial = "g"
case obligatoryMemorial = "G"
case feast = "F"
case solemnity = "H"
public var label: String {
switch self {
case .weekday: "Wochentag"
case .memorial: "Gedenktag"
case .obligatoryMemorial: "Gebotener Gedenktag"
case .feast: "Fest"
case .solemnity: "Hochfest"
}
}
public var shortLabel: String {
switch self {
case .weekday: ""
case .memorial: "g"
case .obligatoryMemorial: "G"
case .feast: "F"
case .solemnity: "H"
}
}
public var priority: Int {
switch self {
case .weekday: 0
case .memorial: 1
case .obligatoryMemorial: 2
case .feast: 3
case .solemnity: 4
}
}
public var isFeast: Bool { self == .feast || self == .solemnity }
public static func < (lhs: LiturgicalRank, rhs: LiturgicalRank) -> Bool {
lhs.priority < rhs.priority
}
}
public enum LiturgicalColor: String, Codable, CaseIterable, Sendable {
case white = "w"
case red = "r"
case green = "g"
case violet = "v"
case rose = "ros"
case black = "s"
case gold = "gold"
public var label: String {
switch self {
case .white: "Weiß"
case .red: "Rot"
case .green: "Grün"
case .violet: "Violett"
case .rose: "Rosa"
case .black: "Schwarz"
case .gold: "Gold"
}
}
public init(apiValue: String) {
switch apiValue.lowercased() {
case "r": self = .red
case "g": self = .green
case "v": self = .violet
case "ros", "rose": self = .rose
case "s", "sw": self = .black
case "gold": self = .gold
default: self = .white
}
}
}
public enum LiturgicalSeason: String, Codable, CaseIterable, Sendable, Identifiable {
case advent
case christmas
case ordinary
case lent
case easter
public var id: String { rawValue }
public var title: String {
switch self {
case .advent: "Advent"
case .christmas: "Weihnachtszeit"
case .ordinary: "Jahreskreis"
case .lent: "Österliche Bußzeit"
case .easter: "Osterzeit"
}
}
public var shortTitle: String {
switch self {
case .advent: "Advent"
case .christmas: "Weihnachten"
case .ordinary: "Jahreskreis"
case .lent: "Fastenzeit"
case .easter: "Osterzeit"
}
}
public var colorHex: String {
switch self {
case .advent: "#6E4B8E"
case .christmas: "#B58A3B"
case .ordinary: "#4F7D5A"
case .lent: "#75516F"
case .easter: "#C9A227"
}
}
}
public enum FeastSymbol: String, Codable, CaseIterable, Sendable {
case cross
case star
case flame
case sun
case lily
case crown
case heart
case book
case candle
case dove
public var symbolName: String {
switch self {
case .cross: "cross.fill"
case .star: "star.fill"
case .flame: "flame.fill"
case .sun: "sun.max.fill"
case .lily: "leaf.fill"
case .crown: "crown.fill"
case .heart: "heart.fill"
case .book: "book.closed.fill"
case .candle: "sparkles"
case .dove: "bird.fill"
}
}
public var label: String {
switch self {
case .cross: "Kreuz"
case .star: "Stern"
case .flame: "Feuer"
case .sun: "Sonne"
case .lily: "Lilie"
case .crown: "Krone"
case .heart: "Herz"
case .book: "Buch"
case .candle: "Licht"
case .dove: "Taube"
}
}
}
public struct Readings: Codable, Hashable, Sendable {
public var first: String
public var psalm: String
public var second: String
public var gospel: String
public init(first: String = "", psalm: String = "", second: String = "", gospel: String = "") {
self.first = first
self.psalm = psalm
self.second = second
self.gospel = gospel
}
public var isEmpty: Bool {
first.isEmpty && psalm.isEmpty && second.isEmpty && gospel.isEmpty
}
public var shortLabel: String {
var parts: [String] = []
if !first.isEmpty { parts.append(first) }
if !second.isEmpty { parts.append(second) }
if !gospel.isEmpty { parts.append(gospel) }
return parts.joined(separator: " · ")
}
public var fullLabel: String {
var lines: [String] = []
if !first.isEmpty { lines.append("1. Lesung: \(first)") }
if !psalm.isEmpty { lines.append("Psalm: \(psalm)") }
if !second.isEmpty { lines.append("2. Lesung: \(second)") }
if !gospel.isEmpty { lines.append("Evangelium: \(gospel)") }
return lines.joined(separator: "\n")
}
}
public struct LiturgicalDay: Identifiable, Codable, Hashable, Sendable {
public var date: Date
public var title: String
public var rank: LiturgicalRank
public var color: LiturgicalColor
public var remark: String
public var readings: Readings
public var isObligation: Bool
public var source: String
public var updatedAt: Date
public var id: String { DayMath.key(date) }
public var dateKey: String { DayMath.key(date) }
public init(
date: Date,
title: String,
rank: LiturgicalRank = .weekday,
color: LiturgicalColor = .green,
remark: String = "",
readings: Readings = Readings(),
isObligation: Bool = false,
source: String = "eucharistiefeier.de",
updatedAt: Date = Date()
) {
self.date = DayMath.normalize(date)
self.title = title
self.rank = rank
self.color = color
self.remark = remark
self.readings = readings
self.isObligation = isObligation
self.source = source
self.updatedAt = updatedAt
}
public var isSunday: Bool { DayMath.isSunday(date) }
public var isHighFeast: Bool { rank == .solemnity || title.localizedCaseInsensitiveContains("Hochfest") }
public var isFeast: Bool { rank.isFeast || isHighFeast }
public var season: LiturgicalSeason { LiturgicalCalendarEngine.season(for: date) }
public var symbol: FeastSymbol {
LiturgicalCalendarEngine.symbol(for: title, rank: rank, date: date)
}
public var displayTitle: String {
if title.isEmpty {
return isSunday ? "Sonntag" : DayMath.longString(date)
}
return title
}
public var badgeText: String {
if isSunday, isObligation { return "Sonntag" }
if rank != .weekday { return rank.label }
if isObligation { return "Gebotener Feiertag" }
return ""
}
}
// MARK: - Views / statistics support
public struct ServiceWithAssignments: Identifiable, Hashable, Sendable {
public var service: ServiceOccurrence
public var church: Church
public var assignments: [Assignment]
public var id: String { service.id }
public init(service: ServiceOccurrence, church: Church, assignments: [Assignment]) {
self.service = service
self.church = church
self.assignments = assignments
}
public func assignments(for role: Role) -> [Assignment] {
assignments.filter { $0.role == role }
}
public func openSlots(for role: Role) -> Int {
max(0, service.requiredCount(for: role) - assignments(for: role).count)
}
public var filledSlots: Int {
assignments.count
}
public var openSlots: Int {
max(0, service.requiredSlots - assignments.count)
}
public var isFullyStaffed: Bool { openSlots == 0 }
}
public struct DayPlanRow: Identifiable, Hashable, Sendable {
public var date: Date
public var liturgicalDay: LiturgicalDay?
public var services: [ServiceWithAssignments]
public var id: String { DayMath.key(date) }
public init(date: Date, liturgicalDay: LiturgicalDay?, services: [ServiceWithAssignments]) {
self.date = DayMath.normalize(date)
self.liturgicalDay = liturgicalDay
self.services = services
}
public var openSlots: Int { services.reduce(0) { $0 + $1.openSlots } }
public var assignmentCount: Int { services.reduce(0) { $0 + $1.assignments.count } }
public var hasServices: Bool { !services.isEmpty }
/// Marks days with at least one assignment beyond the person's preferences.
public var hasBeyondPreferences: Bool {
services.contains { service in
service.assignments.contains(where: \.beyondPreferences)
}
}
}
public struct UnfilledSlot: Identifiable, Hashable, Sendable {
public var service: ServiceOccurrence
public var churchName: String
public var role: Role
public var reason: String
public var id: String { "\(service.id)-\(role.rawValue)" }
}
public struct PersonStat: Identifiable, Hashable, Sendable {
public var person: Person
public var total: Int
public var lectors: Int
public var helpers: Int
public var churchCounts: [String: Int]
public var preferredHits: Int
public var sundayCount: Int
public var lastAssignment: Date?
public var id: String { person.id }
public var preferenceRate: Double {
total == 0 ? 0 : Double(preferredHits) / Double(total)
}
}
public struct ChurchStat: Identifiable, Hashable, Sendable {
public var church: Church
public var assignments: Int
public var services: Int
public var openSlots: Int
public var personCount: Int
public var id: String { church.id }
}
public struct RangeStatistics: Hashable, Sendable {
public var range: DayRange
public var serviceCount: Int
public var assignmentCount: Int
public var openSlots: Int
public var requiredSlots: Int
public var personStats: [PersonStat]
public var churchStats: [ChurchStat]
public var monthlyCounts: [String: Int]
public var sundayServiceCount: Int
public var sundayFilled: Int
public var preferenceHits: Int
public var preferenceEligible: Int
public var absenceDays: Int
public static let empty = RangeStatistics(
range: DayRange(start: DayMath.today(), end: DayMath.today()),
serviceCount: 0,
assignmentCount: 0,
openSlots: 0,
requiredSlots: 0,
personStats: [],
churchStats: [],
monthlyCounts: [:],
sundayServiceCount: 0,
sundayFilled: 0,
preferenceHits: 0,
preferenceEligible: 0,
absenceDays: 0
)
public var coverageRate: Double {
requiredSlots == 0 ? 1 : Double(assignmentCount) / Double(requiredSlots)
}
public var preferenceRate: Double {
preferenceEligible == 0 ? 0 : Double(preferenceHits) / Double(preferenceEligible)
}
public var activePeople: Int { personStats.filter { $0.total > 0 }.count }
public var averageAssignments: Double {
let active = personStats.filter { $0.total > 0 }
guard !active.isEmpty else { return 0 }
return Double(active.reduce(0) { $0 + $1.total }) / Double(active.count)
}
}
// MARK: - Import / export
public enum ExchangeScope: String, Codable, CaseIterable, Sendable {
case resources
case plan
public var title: String {
switch self {
case .resources: "Ressourcen"
case .plan: "Planungsabschnitt"
}
}
}
public struct ResourceBundle: Codable, Hashable, Sendable {
public var churches: [Church]
public var people: [Person]
public var absences: [Absence]
public var templates: [ServiceTemplate]
public var exceptions: [ServiceException]
public init(
churches: [Church] = [],
people: [Person] = [],
absences: [Absence] = [],
templates: [ServiceTemplate] = [],
exceptions: [ServiceException] = []
) {
self.churches = churches
self.people = people
self.absences = absences
self.templates = templates
self.exceptions = exceptions
}
}
public struct PlanExchange: Codable, Sendable {
public var formatVersion: Int
public var exportedAt: Date
public var appName: String
public var scope: ExchangeScope
public var range: DayRange
public var resources: ResourceBundle
public var services: [ServiceOccurrence]
public var assignments: [Assignment]
public var liturgicalDays: [LiturgicalDay]
public var note: String
public init(
formatVersion: Int = 1,
exportedAt: Date = Date(),
appName: String = "LektorenPlan",
scope: ExchangeScope,
range: DayRange,
resources: ResourceBundle,
services: [ServiceOccurrence] = [],
assignments: [Assignment] = [],
liturgicalDays: [LiturgicalDay] = [],
note: String = ""
) {
self.formatVersion = formatVersion
self.exportedAt = exportedAt
self.appName = appName
self.scope = scope
self.range = range
self.resources = resources
self.services = services
self.assignments = assignments
self.liturgicalDays = liturgicalDays
self.note = note
}
public var summary: ExchangeSummary {
ExchangeSummary(
scope: scope,
range: range,
churches: resources.churches.count,
people: resources.people.count,
templates: resources.templates.count,
services: services.count,
assignments: assignments.count,
liturgicalDays: liturgicalDays.count
)
}
}
public struct ExchangeSummary: Hashable, Sendable {
public var scope: ExchangeScope
public var range: DayRange
public var churches: Int
public var people: Int
public var templates: Int
public var services: Int
public var assignments: Int
public var liturgicalDays: Int
}
// MARK: - Planning
public struct PlannerOptions: Codable, Hashable, Sendable {
public var replaceExisting: Bool
public var respectPreferredWeekdays: Bool
public var allowBeyondPreferences: Bool
public var allowDoubleRolesOnSameDay: Bool
public var weightChurchPreference: Double
public var weightServicePreference: Double
public var weightFairness: Double
public var weightDualRolePreference: Double
public var maxAssignmentsPerDay: Int
public init(
replaceExisting: Bool = false,
respectPreferredWeekdays: Bool = true,
allowBeyondPreferences: Bool = false,
allowDoubleRolesOnSameDay: Bool = false,
weightChurchPreference: Double = 8,
weightServicePreference: Double = 4,
weightFairness: Double = 2.2,
weightDualRolePreference: Double = 14,
maxAssignmentsPerDay: Int = 1
) {
self.replaceExisting = replaceExisting
self.respectPreferredWeekdays = respectPreferredWeekdays
self.allowBeyondPreferences = allowBeyondPreferences
self.allowDoubleRolesOnSameDay = allowDoubleRolesOnSameDay
self.weightChurchPreference = weightChurchPreference
self.weightServicePreference = weightServicePreference
self.weightFairness = weightFairness
self.weightDualRolePreference = weightDualRolePreference
self.maxAssignmentsPerDay = maxAssignmentsPerDay
}
private enum CodingKeys: String, CodingKey {
case replaceExisting, respectPreferredWeekdays, allowBeyondPreferences
case allowDoubleRolesOnSameDay, weightChurchPreference, weightServicePreference
case weightFairness, weightDualRolePreference, maxAssignmentsPerDay
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
replaceExisting = try container.decodeIfPresent(Bool.self, forKey: .replaceExisting) ?? false
respectPreferredWeekdays = try container.decodeIfPresent(Bool.self, forKey: .respectPreferredWeekdays) ?? true
allowBeyondPreferences = try container.decodeIfPresent(Bool.self, forKey: .allowBeyondPreferences) ?? false
allowDoubleRolesOnSameDay = try container.decodeIfPresent(Bool.self, forKey: .allowDoubleRolesOnSameDay) ?? false
weightChurchPreference = try container.decodeIfPresent(Double.self, forKey: .weightChurchPreference) ?? 8
weightServicePreference = try container.decodeIfPresent(Double.self, forKey: .weightServicePreference) ?? 4
weightFairness = try container.decodeIfPresent(Double.self, forKey: .weightFairness) ?? 2.2
weightDualRolePreference = try container.decodeIfPresent(Double.self, forKey: .weightDualRolePreference) ?? 14
maxAssignmentsPerDay = try container.decodeIfPresent(Int.self, forKey: .maxAssignmentsPerDay) ?? 1
}
}
public struct PlanResult: Sendable {
public var assignments: [Assignment]
public var unfilled: [UnfilledSlot]
public var filledCount: Int
public var message: String
public init(assignments: [Assignment] = [], unfilled: [UnfilledSlot] = [], filledCount: Int = 0, message: String = "") {
self.assignments = assignments
self.unfilled = unfilled
self.filledCount = filledCount
self.message = message
}
}