1. Prototyp
This commit is contained in:
1 parent
e723eee440
commit
c24bc91768
37 files changed
+11610
No files matched your search
@@ -0,0 +1,756 @@
|
||||
import Foundation
|
||||
|
||||
public final class AppDatabase {
|
||||
public let database: SQLiteDatabase
|
||||
public let path: String
|
||||
private let encoder = JSONEncoder()
|
||||
private let decoder = JSONDecoder()
|
||||
|
||||
public init(path: String, seedDemo: Bool = true) throws {
|
||||
self.path = path
|
||||
self.database = try SQLiteDatabase(path: path)
|
||||
try migrate()
|
||||
if seedDemo, try churchCount() == 0 {
|
||||
try DemoData.seed(into: self)
|
||||
}
|
||||
}
|
||||
|
||||
public static func defaultPath() -> String {
|
||||
let fm = FileManager.default
|
||||
let base = fm.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
||||
?? fm.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support")
|
||||
let folder = base.appendingPathComponent("LektorenPlan", isDirectory: true)
|
||||
try? fm.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
return folder.appendingPathComponent("lektorenplan.sqlite").path
|
||||
}
|
||||
|
||||
public static func makeInMemory(seedDemo: Bool = false) throws -> AppDatabase {
|
||||
try AppDatabase(path: ":memory:", seedDemo: seedDemo)
|
||||
}
|
||||
|
||||
private func migrate() throws {
|
||||
let schema = """
|
||||
CREATE TABLE IF NOT EXISTS churches (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
short_name TEXT NOT NULL,
|
||||
symbol TEXT NOT NULL,
|
||||
color_hex TEXT NOT NULL,
|
||||
address TEXT NOT NULL DEFAULT '',
|
||||
sort_index INTEGER NOT NULL DEFAULT 0,
|
||||
notes TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS people (
|
||||
id TEXT PRIMARY KEY,
|
||||
first_name TEXT NOT NULL,
|
||||
last_name TEXT NOT NULL,
|
||||
roles TEXT NOT NULL,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
phone TEXT NOT NULL DEFAULT '',
|
||||
preferred_church_ids TEXT NOT NULL DEFAULT '[]',
|
||||
preferred_weekdays TEXT NOT NULL DEFAULT '[]',
|
||||
preferred_service_titles TEXT NOT NULL DEFAULT '[]',
|
||||
max_per_month INTEGER NOT NULL DEFAULT 6,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
notes TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS absences (
|
||||
id TEXT PRIMARY KEY,
|
||||
person_id TEXT NOT NULL REFERENCES people(id) ON DELETE CASCADE,
|
||||
start_date TEXT NOT NULL,
|
||||
end_date TEXT NOT NULL,
|
||||
reason TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_absences_person ON absences(person_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS service_templates (
|
||||
id TEXT PRIMARY KEY,
|
||||
church_id TEXT NOT NULL REFERENCES churches(id) ON DELETE CASCADE,
|
||||
weekday INTEGER NOT NULL,
|
||||
time_minutes INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
lectors_needed INTEGER NOT NULL DEFAULT 1,
|
||||
helpers_needed INTEGER NOT NULL DEFAULT 1,
|
||||
valid_from TEXT NOT NULL,
|
||||
valid_to TEXT,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
notes TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_templates_church ON service_templates(church_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS service_exceptions (
|
||||
id TEXT PRIMARY KEY,
|
||||
template_id TEXT NOT NULL REFERENCES service_templates(id) ON DELETE CASCADE,
|
||||
date TEXT NOT NULL,
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
UNIQUE(template_id, date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS services (
|
||||
id TEXT PRIMARY KEY,
|
||||
church_id TEXT NOT NULL REFERENCES churches(id) ON DELETE CASCADE,
|
||||
template_id TEXT REFERENCES service_templates(id) ON DELETE SET NULL,
|
||||
date TEXT NOT NULL,
|
||||
time_minutes INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
lectors_needed INTEGER NOT NULL DEFAULT 1,
|
||||
helpers_needed INTEGER NOT NULL DEFAULT 1,
|
||||
kind TEXT NOT NULL DEFAULT 'regular',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
locked INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_services_date ON services(date);
|
||||
CREATE INDEX IF NOT EXISTS idx_services_church ON services(church_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_services_template_date
|
||||
ON services(template_id, date) WHERE template_id IS NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS assignments (
|
||||
id TEXT PRIMARY KEY,
|
||||
service_id TEXT NOT NULL REFERENCES services(id) ON DELETE CASCADE,
|
||||
person_id TEXT NOT NULL REFERENCES people(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL,
|
||||
locked INTEGER NOT NULL DEFAULT 0,
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
UNIQUE(service_id, person_id, role)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_assignments_service ON assignments(service_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_assignments_person ON assignments(person_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS liturgical_days (
|
||||
date TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
rank TEXT NOT NULL DEFAULT '',
|
||||
color TEXT NOT NULL DEFAULT 'g',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
first_reading TEXT NOT NULL DEFAULT '',
|
||||
psalm TEXT NOT NULL DEFAULT '',
|
||||
second_reading TEXT NOT NULL DEFAULT '',
|
||||
gospel TEXT NOT NULL DEFAULT '',
|
||||
is_obligation INTEGER NOT NULL DEFAULT 0,
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_liturgical_date ON liturgical_days(date);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
try database.execute(schema)
|
||||
try database.run("INSERT OR IGNORE INTO settings(key, value) VALUES('schemaVersion', '1')")
|
||||
}
|
||||
|
||||
// MARK: - Churches
|
||||
|
||||
public func churchCount() throws -> Int {
|
||||
try database.scalarInt("SELECT COUNT(*) AS value FROM churches")
|
||||
}
|
||||
|
||||
public func churches() throws -> [Church] {
|
||||
try database.query("SELECT * FROM churches ORDER BY sort_index, name").compactMap { row in
|
||||
guard let id = row.string("id"),
|
||||
let name = row.string("name"),
|
||||
let shortName = row.string("short_name"),
|
||||
let symbolRaw = row.string("symbol")
|
||||
else { return nil }
|
||||
return Church(
|
||||
id: id,
|
||||
name: name,
|
||||
shortName: shortName,
|
||||
symbol: ChurchSymbol(rawValue: symbolRaw) ?? .chapel,
|
||||
colorHex: row.string("color_hex", default: "#2F5D62"),
|
||||
address: row.string("address", default: ""),
|
||||
sortIndex: row.int("sort_index", default: 0),
|
||||
notes: row.string("notes", default: "")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public func upsert(_ church: Church) throws {
|
||||
try database.run("""
|
||||
INSERT INTO churches(id, name, short_name, symbol, color_hex, address, sort_index, notes)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
name=excluded.name, short_name=excluded.short_name, symbol=excluded.symbol,
|
||||
color_hex=excluded.color_hex, address=excluded.address,
|
||||
sort_index=excluded.sort_index, notes=excluded.notes
|
||||
""", [
|
||||
.text(church.id), .text(church.name), .text(church.shortName),
|
||||
.text(church.symbol.rawValue), .text(church.colorHex), .text(church.address),
|
||||
.int(church.sortIndex), .text(church.notes)
|
||||
])
|
||||
}
|
||||
|
||||
public func deleteChurch(id: String) throws {
|
||||
try database.run("DELETE FROM churches WHERE id=?", [.text(id)])
|
||||
}
|
||||
|
||||
// MARK: - People
|
||||
|
||||
public func people() throws -> [Person] {
|
||||
try database.query("SELECT * FROM people ORDER BY last_name, first_name").compactMap { decodePerson($0) }
|
||||
}
|
||||
|
||||
public func person(id: String) throws -> Person? {
|
||||
try database.query("SELECT * FROM people WHERE id=?", [.text(id)]).first.flatMap(decodePerson)
|
||||
}
|
||||
|
||||
public func upsert(_ person: Person) throws {
|
||||
let roles = encode(person.roles.map(\.rawValue).sorted())
|
||||
let churches = encode(person.preferredChurchIDs.sorted())
|
||||
let weekdays = encode(person.preferredWeekdays.sorted())
|
||||
let titles = encode(person.preferredServiceTitles)
|
||||
try database.run("""
|
||||
INSERT INTO people(id, first_name, last_name, roles, email, phone, preferred_church_ids,
|
||||
preferred_weekdays, preferred_service_titles, max_per_month, active, notes)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
first_name=excluded.first_name, last_name=excluded.last_name, roles=excluded.roles,
|
||||
email=excluded.email, phone=excluded.phone,
|
||||
preferred_church_ids=excluded.preferred_church_ids,
|
||||
preferred_weekdays=excluded.preferred_weekdays,
|
||||
preferred_service_titles=excluded.preferred_service_titles,
|
||||
max_per_month=excluded.max_per_month, active=excluded.active, notes=excluded.notes
|
||||
""", [
|
||||
.text(person.id), .text(person.firstName), .text(person.lastName), .text(roles),
|
||||
.text(person.email), .text(person.phone), .text(churches), .text(weekdays),
|
||||
.text(titles), .int(person.maxPerMonth), .bool(person.active), .text(person.notes)
|
||||
])
|
||||
}
|
||||
|
||||
public func deletePerson(id: String) throws {
|
||||
try database.run("DELETE FROM people WHERE id=?", [.text(id)])
|
||||
}
|
||||
|
||||
private func decodePerson(_ row: SQLiteRow) -> Person? {
|
||||
guard let id = row.string("id"),
|
||||
let first = row.string("first_name"),
|
||||
let last = row.string("last_name")
|
||||
else { return nil }
|
||||
let roleStrings: [String] = decode(row.string("roles", default: "[]"))
|
||||
return Person(
|
||||
id: id,
|
||||
firstName: first,
|
||||
lastName: last,
|
||||
roles: Set(roleStrings.compactMap(Role.init(rawValue:))),
|
||||
email: row.string("email", default: ""),
|
||||
phone: row.string("phone", default: ""),
|
||||
preferredChurchIDs: Set(decode(row.string("preferred_church_ids", default: "[]")) as [String]),
|
||||
preferredWeekdays: Set(decode(row.string("preferred_weekdays", default: "[]")) as [Int]),
|
||||
preferredServiceTitles: decode(row.string("preferred_service_titles", default: "[]")),
|
||||
maxPerMonth: row.int("max_per_month", default: 6),
|
||||
active: row.bool("active", default: true),
|
||||
notes: row.string("notes", default: "")
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Absences
|
||||
|
||||
public func absences() throws -> [Absence] {
|
||||
try database.query("SELECT * FROM absences ORDER BY start_date").compactMap { row in
|
||||
guard let id = row.string("id"), let personID = row.string("person_id"),
|
||||
let start = row.date("start_date"), let end = row.date("end_date")
|
||||
else { return nil }
|
||||
return Absence(id: id, personID: personID, start: start, end: end, reason: row.string("reason", default: ""))
|
||||
}
|
||||
}
|
||||
|
||||
public func absences(personID: String) throws -> [Absence] {
|
||||
try database.query("SELECT * FROM absences WHERE person_id=? ORDER BY start_date", [.text(personID)]).compactMap { row in
|
||||
guard let id = row.string("id"), let start = row.date("start_date"), let end = row.date("end_date") else { return nil }
|
||||
return Absence(id: id, personID: personID, start: start, end: end, reason: row.string("reason", default: ""))
|
||||
}
|
||||
}
|
||||
|
||||
public func upsert(_ absence: Absence) throws {
|
||||
try database.run("""
|
||||
INSERT INTO absences(id, person_id, start_date, end_date, reason) VALUES(?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET person_id=excluded.person_id, start_date=excluded.start_date,
|
||||
end_date=excluded.end_date, reason=excluded.reason
|
||||
""", [
|
||||
.text(absence.id), .text(absence.personID), .dateKey(absence.start),
|
||||
.dateKey(absence.end), .text(absence.reason)
|
||||
])
|
||||
}
|
||||
|
||||
public func deleteAbsence(id: String) throws {
|
||||
try database.run("DELETE FROM absences WHERE id=?", [.text(id)])
|
||||
}
|
||||
|
||||
// MARK: - Service templates
|
||||
|
||||
public func templates() throws -> [ServiceTemplate] {
|
||||
try database.query("SELECT * FROM service_templates ORDER BY weekday, time_minutes").compactMap { row in
|
||||
guard let id = row.string("id"), let churchID = row.string("church_id"),
|
||||
let title = row.string("title"), let from = row.date("valid_from")
|
||||
else { return nil }
|
||||
return ServiceTemplate(
|
||||
id: id,
|
||||
churchID: churchID,
|
||||
weekday: row.int("weekday", default: 1),
|
||||
timeMinutes: row.int("time_minutes", default: 600),
|
||||
title: title,
|
||||
lectorsNeeded: row.int("lectors_needed", default: 1),
|
||||
helpersNeeded: row.int("helpers_needed", default: 1),
|
||||
validFrom: from,
|
||||
validTo: row.date("valid_to"),
|
||||
active: row.bool("active", default: true),
|
||||
notes: row.string("notes", default: "")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public func upsert(_ template: ServiceTemplate) throws {
|
||||
try database.run("""
|
||||
INSERT INTO service_templates(id, church_id, weekday, time_minutes, title, lectors_needed,
|
||||
helpers_needed, valid_from, valid_to, active, notes)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET church_id=excluded.church_id, weekday=excluded.weekday,
|
||||
time_minutes=excluded.time_minutes, title=excluded.title,
|
||||
lectors_needed=excluded.lectors_needed, helpers_needed=excluded.helpers_needed,
|
||||
valid_from=excluded.valid_from, valid_to=excluded.valid_to,
|
||||
active=excluded.active, notes=excluded.notes
|
||||
""", [
|
||||
.text(template.id), .text(template.churchID), .int(template.weekday),
|
||||
.int(template.timeMinutes), .text(template.title), .int(template.lectorsNeeded),
|
||||
.int(template.helpersNeeded), .dateKey(template.validFrom),
|
||||
template.validTo.map(SQLiteValue.dateKey) ?? .null,
|
||||
.bool(template.active), .text(template.notes)
|
||||
])
|
||||
}
|
||||
|
||||
public func deleteTemplate(id: String) throws {
|
||||
try database.run("DELETE FROM service_templates WHERE id=?", [.text(id)])
|
||||
}
|
||||
|
||||
// MARK: - Exceptions
|
||||
|
||||
public func exceptions() throws -> [ServiceException] {
|
||||
try database.query("SELECT * FROM service_exceptions ORDER BY date").compactMap { row in
|
||||
guard let id = row.string("id"), let templateID = row.string("template_id"), let date = row.date("date") else { return nil }
|
||||
return ServiceException(id: id, templateID: templateID, date: date, reason: row.string("reason", default: ""))
|
||||
}
|
||||
}
|
||||
|
||||
public func upsert(_ exception: ServiceException) throws {
|
||||
try database.run("""
|
||||
INSERT INTO service_exceptions(id, template_id, date, reason) VALUES(?, ?, ?, ?)
|
||||
ON CONFLICT(template_id, date) DO UPDATE SET reason=excluded.reason
|
||||
""", [.text(exception.id), .text(exception.templateID), .dateKey(exception.date), .text(exception.reason)])
|
||||
}
|
||||
|
||||
public func deleteException(id: String) throws {
|
||||
try database.run("DELETE FROM service_exceptions WHERE id=?", [.text(id)])
|
||||
}
|
||||
|
||||
// MARK: - Services
|
||||
|
||||
public func services(in range: DayRange) throws -> [ServiceOccurrence] {
|
||||
try database.query("""
|
||||
SELECT * FROM services WHERE date >= ? AND date <= ?
|
||||
ORDER BY date, time_minutes, church_id
|
||||
""", [.dateKey(range.start), .dateKey(range.end)]).compactMap(decodeService)
|
||||
}
|
||||
|
||||
public func services(on date: Date) throws -> [ServiceOccurrence] {
|
||||
try database.query("SELECT * FROM services WHERE date=? ORDER BY time_minutes", [.dateKey(date)]).compactMap(decodeService)
|
||||
}
|
||||
|
||||
public func service(id: String) throws -> ServiceOccurrence? {
|
||||
try database.query("SELECT * FROM services WHERE id=?", [.text(id)]).first.flatMap(decodeService)
|
||||
}
|
||||
|
||||
public func specialServices() throws -> [ServiceOccurrence] {
|
||||
try database.query("SELECT * FROM services WHERE kind='special' ORDER BY date, time_minutes").compactMap(decodeService)
|
||||
}
|
||||
|
||||
public func serviceCount() throws -> Int {
|
||||
try database.scalarInt("SELECT COUNT(*) AS value FROM services")
|
||||
}
|
||||
|
||||
public func upsert(_ service: ServiceOccurrence) throws {
|
||||
try database.run("""
|
||||
INSERT INTO services(id, church_id, template_id, date, time_minutes, title, lectors_needed,
|
||||
helpers_needed, kind, notes, locked, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET church_id=excluded.church_id, template_id=excluded.template_id,
|
||||
date=excluded.date, time_minutes=excluded.time_minutes, title=excluded.title,
|
||||
lectors_needed=excluded.lectors_needed, helpers_needed=excluded.helpers_needed,
|
||||
kind=excluded.kind, notes=excluded.notes, locked=excluded.locked
|
||||
""", [
|
||||
.text(service.id), .text(service.churchID), service.templateID.map(SQLiteValue.text) ?? .null,
|
||||
.dateKey(service.date), .int(service.timeMinutes), .text(service.title),
|
||||
.int(service.lectorsNeeded), .int(service.helpersNeeded), .text(service.kind.rawValue),
|
||||
.text(service.notes), .bool(service.locked), .text(ISO8601DateFormatter().string(from: service.createdAt))
|
||||
])
|
||||
}
|
||||
|
||||
public func deleteService(id: String) throws {
|
||||
try database.run("DELETE FROM services WHERE id=?", [.text(id)])
|
||||
}
|
||||
|
||||
private func decodeService(_ row: SQLiteRow) -> ServiceOccurrence? {
|
||||
guard let id = row.string("id"), let churchID = row.string("church_id"),
|
||||
let date = row.date("date"), let title = row.string("title")
|
||||
else { return nil }
|
||||
return ServiceOccurrence(
|
||||
id: id,
|
||||
churchID: churchID,
|
||||
templateID: row.string("template_id"),
|
||||
date: date,
|
||||
timeMinutes: row.int("time_minutes", default: 600),
|
||||
title: title,
|
||||
lectorsNeeded: row.int("lectors_needed", default: 1),
|
||||
helpersNeeded: row.int("helpers_needed", default: 1),
|
||||
kind: ServiceKind(rawValue: row.string("kind", default: "regular")) ?? .regular,
|
||||
notes: row.string("notes", default: ""),
|
||||
locked: row.bool("locked", default: false),
|
||||
createdAt: ISO8601DateFormatter().date(from: row.string("created_at", default: "")) ?? Date()
|
||||
)
|
||||
}
|
||||
|
||||
/// Generates regular occurrences from the current service order. Existing occurrences
|
||||
/// that already have assignments are never overwritten.
|
||||
@discardableResult
|
||||
public func generateServices(in range: DayRange, regenerateUnassigned: Bool = true) throws -> Int {
|
||||
let allTemplates = try templates()
|
||||
let allExceptions = try exceptions()
|
||||
let exceptionKeys = Set(allExceptions.map { "\($0.templateID)|\(DayMath.key($0.date))" })
|
||||
let existing = try services(in: range)
|
||||
var existingByTemplate: [String: ServiceOccurrence] = [:]
|
||||
for service in existing {
|
||||
if let templateID = service.templateID {
|
||||
existingByTemplate["\(templateID)|\(service.dateKey)"] = service
|
||||
}
|
||||
}
|
||||
var created = 0
|
||||
|
||||
try database.transaction {
|
||||
for day in range.days {
|
||||
for template in allTemplates where template.isValid(on: day) {
|
||||
let key = "\(template.id)|\(DayMath.key(day))"
|
||||
if exceptionKeys.contains(key) { continue }
|
||||
if let existing = existingByTemplate[key] {
|
||||
guard regenerateUnassigned else { continue }
|
||||
let assignmentCount = try assignmentCount(serviceID: existing.id)
|
||||
if assignmentCount == 0 {
|
||||
var updated = existing
|
||||
updated.timeMinutes = template.timeMinutes
|
||||
updated.title = template.title
|
||||
updated.lectorsNeeded = template.lectorsNeeded
|
||||
updated.helpersNeeded = template.helpersNeeded
|
||||
try upsert(updated)
|
||||
}
|
||||
continue
|
||||
}
|
||||
let service = ServiceOccurrence(
|
||||
churchID: template.churchID,
|
||||
templateID: template.id,
|
||||
date: day,
|
||||
timeMinutes: template.timeMinutes,
|
||||
title: template.title,
|
||||
lectorsNeeded: template.lectorsNeeded,
|
||||
helpersNeeded: template.helpersNeeded,
|
||||
kind: .regular,
|
||||
notes: template.notes
|
||||
)
|
||||
try upsert(service)
|
||||
created += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return created
|
||||
}
|
||||
|
||||
private func assignmentCount(serviceID: String) throws -> Int {
|
||||
try database.scalarInt("SELECT COUNT(*) AS value FROM assignments WHERE service_id=?", [.text(serviceID)])
|
||||
}
|
||||
|
||||
// MARK: - Assignments
|
||||
|
||||
public func assignments(in range: DayRange) throws -> [Assignment] {
|
||||
try database.query("""
|
||||
SELECT a.* FROM assignments a JOIN services s ON s.id = a.service_id
|
||||
WHERE s.date >= ? AND s.date <= ?
|
||||
ORDER BY s.date, s.time_minutes
|
||||
""", [.dateKey(range.start), .dateKey(range.end)]).compactMap(decodeAssignment)
|
||||
}
|
||||
|
||||
public func assignments(serviceIDs: [String]) throws -> [Assignment] {
|
||||
guard !serviceIDs.isEmpty else { return [] }
|
||||
let placeholders = Array(repeating: "?", count: serviceIDs.count).joined(separator: ",")
|
||||
return try database.query(
|
||||
"SELECT * FROM assignments WHERE service_id IN (\(placeholders))",
|
||||
serviceIDs.map(SQLiteValue.text)
|
||||
).compactMap(decodeAssignment)
|
||||
}
|
||||
|
||||
public func assignments(personID: String) throws -> [Assignment] {
|
||||
try database.query("SELECT * FROM assignments WHERE person_id=?", [.text(personID)]).compactMap(decodeAssignment)
|
||||
}
|
||||
|
||||
public func assignmentCount() throws -> Int {
|
||||
try database.scalarInt("SELECT COUNT(*) AS value FROM assignments")
|
||||
}
|
||||
|
||||
public func upsert(_ assignment: Assignment) throws {
|
||||
try database.run("""
|
||||
INSERT INTO assignments(id, service_id, person_id, role, locked, note, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET service_id=excluded.service_id, person_id=excluded.person_id,
|
||||
role=excluded.role, locked=excluded.locked, note=excluded.note
|
||||
""", [
|
||||
.text(assignment.id), .text(assignment.serviceID), .text(assignment.personID),
|
||||
.text(assignment.role.rawValue), .bool(assignment.locked), .text(assignment.note),
|
||||
.text(ISO8601DateFormatter().string(from: assignment.createdAt))
|
||||
])
|
||||
}
|
||||
|
||||
/// Replaces the assignment for one role of a service. Passing nil clears the slot.
|
||||
public func setAssignment(serviceID: String, role: Role, personID: String?, locked: Bool = false) throws {
|
||||
try database.transaction {
|
||||
try database.run("DELETE FROM assignments WHERE service_id=? AND role=?", [.text(serviceID), .text(role.rawValue)])
|
||||
guard let personID else { return }
|
||||
let assignment = Assignment(serviceID: serviceID, personID: personID, role: role, locked: locked)
|
||||
try upsert(assignment)
|
||||
}
|
||||
}
|
||||
|
||||
public func setAssignment(serviceID: String, personID: String?, role: Role, locked: Bool = false) throws {
|
||||
try setAssignment(serviceID: serviceID, role: role, personID: personID, locked: locked)
|
||||
}
|
||||
|
||||
public func deleteAssignment(id: String) throws {
|
||||
try database.run("DELETE FROM assignments WHERE id=?", [.text(id)])
|
||||
}
|
||||
|
||||
public func toggleAssignmentLock(id: String) throws {
|
||||
try database.run("UPDATE assignments SET locked = CASE locked WHEN 0 THEN 1 ELSE 0 END WHERE id=?", [.text(id)])
|
||||
}
|
||||
|
||||
public func savePlan(_ assignments: [Assignment], in range: DayRange, replaceUnlocked: Bool) throws {
|
||||
let serviceIDs = try services(in: range).map(\.id)
|
||||
try database.transaction {
|
||||
if replaceUnlocked, !serviceIDs.isEmpty {
|
||||
let placeholders = Array(repeating: "?", count: serviceIDs.count).joined(separator: ",")
|
||||
try database.run(
|
||||
"DELETE FROM assignments WHERE locked=0 AND service_id IN (\(placeholders))",
|
||||
serviceIDs.map(SQLiteValue.text)
|
||||
)
|
||||
}
|
||||
for assignment in assignments {
|
||||
try upsert(assignment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func decodeAssignment(_ row: SQLiteRow) -> Assignment? {
|
||||
guard let id = row.string("id"), let serviceID = row.string("service_id"),
|
||||
let personID = row.string("person_id"), let roleRaw = row.string("role"),
|
||||
let role = Role(rawValue: roleRaw)
|
||||
else { return nil }
|
||||
return Assignment(
|
||||
id: id,
|
||||
serviceID: serviceID,
|
||||
personID: personID,
|
||||
role: role,
|
||||
locked: row.bool("locked", default: false),
|
||||
note: row.string("note", default: ""),
|
||||
createdAt: ISO8601DateFormatter().date(from: row.string("created_at", default: "")) ?? Date()
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Liturgical days
|
||||
|
||||
public func liturgicalDays(in range: DayRange) throws -> [LiturgicalDay] {
|
||||
try database.query("SELECT * FROM liturgical_days WHERE date >= ? AND date <= ? ORDER BY date",
|
||||
[.dateKey(range.start), .dateKey(range.end)]).compactMap(decodeLiturgicalDay)
|
||||
}
|
||||
|
||||
public func liturgicalDay(on date: Date) throws -> LiturgicalDay? {
|
||||
try database.query("SELECT * FROM liturgical_days WHERE date=?", [.dateKey(date)]).first.flatMap(decodeLiturgicalDay)
|
||||
}
|
||||
|
||||
public func liturgicalDayCount() throws -> Int {
|
||||
try database.scalarInt("SELECT COUNT(*) AS value FROM liturgical_days")
|
||||
}
|
||||
|
||||
public func liturgicalYears() throws -> [Int] {
|
||||
try database.query("SELECT DISTINCT substr(date,1,4) AS year FROM liturgical_days ORDER BY year").compactMap {
|
||||
Int($0.string("year", default: "0"))
|
||||
}
|
||||
}
|
||||
|
||||
public func upsert(liturgicalDay: LiturgicalDay) throws {
|
||||
try database.run("""
|
||||
INSERT INTO liturgical_days(date, title, rank, color, remark, first_reading, psalm,
|
||||
second_reading, gospel, is_obligation, source, updated_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(date) DO UPDATE SET title=excluded.title, rank=excluded.rank, color=excluded.color,
|
||||
remark=excluded.remark, first_reading=excluded.first_reading, psalm=excluded.psalm,
|
||||
second_reading=excluded.second_reading, gospel=excluded.gospel,
|
||||
is_obligation=excluded.is_obligation, source=excluded.source, updated_at=excluded.updated_at
|
||||
""", [
|
||||
.dateKey(liturgicalDay.date), .text(liturgicalDay.title), .text(liturgicalDay.rank.rawValue),
|
||||
.text(liturgicalDay.color.rawValue), .text(liturgicalDay.remark),
|
||||
.text(liturgicalDay.readings.first), .text(liturgicalDay.readings.psalm),
|
||||
.text(liturgicalDay.readings.second), .text(liturgicalDay.readings.gospel),
|
||||
.bool(liturgicalDay.isObligation), .text(liturgicalDay.source),
|
||||
.text(ISO8601DateFormatter().string(from: liturgicalDay.updatedAt))
|
||||
])
|
||||
}
|
||||
|
||||
public func upsert(liturgicalDays days: [LiturgicalDay]) throws {
|
||||
try database.transaction {
|
||||
for day in days { try upsert(liturgicalDay: day) }
|
||||
}
|
||||
}
|
||||
|
||||
public func replaceLiturgicalYear(_ year: Int, with days: [LiturgicalDay]) throws {
|
||||
try database.transaction {
|
||||
try database.run("DELETE FROM liturgical_days WHERE date LIKE ?", [.text("\(year)-%")])
|
||||
for day in days { try upsert(liturgicalDay: day) }
|
||||
}
|
||||
}
|
||||
|
||||
private func decodeLiturgicalDay(_ row: SQLiteRow) -> LiturgicalDay? {
|
||||
guard let date = row.date("date") else { return nil }
|
||||
return LiturgicalDay(
|
||||
date: date,
|
||||
title: row.string("title", default: ""),
|
||||
rank: LiturgicalRank(rawValue: row.string("rank", default: "")) ?? .weekday,
|
||||
color: LiturgicalColor(rawValue: row.string("color", default: "g")) ?? .green,
|
||||
remark: row.string("remark", default: ""),
|
||||
readings: Readings(
|
||||
first: row.string("first_reading", default: ""),
|
||||
psalm: row.string("psalm", default: ""),
|
||||
second: row.string("second_reading", default: ""),
|
||||
gospel: row.string("gospel", default: "")
|
||||
),
|
||||
isObligation: row.bool("is_obligation"),
|
||||
source: row.string("source", default: ""),
|
||||
updatedAt: ISO8601DateFormatter().date(from: row.string("updated_at", default: "")) ?? Date()
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Settings
|
||||
|
||||
public func setting(_ key: String) -> String? {
|
||||
guard let row = try? database.query("SELECT value FROM settings WHERE key=?", [.text(key)]).first else { return nil }
|
||||
return row.string("value")
|
||||
}
|
||||
|
||||
public func setSetting(_ key: String, value: String) {
|
||||
try? database.run("INSERT INTO settings(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
||||
[.text(key), .text(value)])
|
||||
}
|
||||
|
||||
public func removeSetting(_ key: String) {
|
||||
try? database.run("DELETE FROM settings WHERE key=?", [.text(key)])
|
||||
}
|
||||
|
||||
// MARK: - Resources / exchange
|
||||
|
||||
public func resources() throws -> ResourceBundle {
|
||||
ResourceBundle(
|
||||
churches: try churches(),
|
||||
people: try people(),
|
||||
absences: try absences(),
|
||||
templates: try templates(),
|
||||
exceptions: try exceptions()
|
||||
)
|
||||
}
|
||||
|
||||
public func applyResourceBundle(_ bundle: ResourceBundle, replaceExisting: Bool = false) throws {
|
||||
try database.transaction {
|
||||
if replaceExisting {
|
||||
for template in try templates() { try deleteTemplate(id: template.id) }
|
||||
for person in try people() { try deletePerson(id: person.id) }
|
||||
for church in try churches() { try deleteChurch(id: church.id) }
|
||||
}
|
||||
for church in bundle.churches { try upsert(church) }
|
||||
for person in bundle.people { try upsert(person) }
|
||||
for absence in bundle.absences { try upsert(absence) }
|
||||
for template in bundle.templates { try upsert(template) }
|
||||
for exception in bundle.exceptions { try upsert(exception) }
|
||||
}
|
||||
}
|
||||
|
||||
public func exportPlan(range: DayRange, scope: ExchangeScope = .plan) throws -> PlanExchange {
|
||||
let services = scope == .resources ? [] : try services(in: range)
|
||||
let serviceIDs = services.map(\.id)
|
||||
let assignments = scope == .resources ? [] : try assignments(serviceIDs: serviceIDs)
|
||||
let peopleIDs = Set(assignments.map(\.personID))
|
||||
let allPeople = try people()
|
||||
let relevantPeople = scope == .resources ? allPeople : allPeople.filter { peopleIDs.contains($0.id) }
|
||||
let allAbsences = try absences()
|
||||
let relevantAbsences = scope == .resources ? allAbsences : allAbsences.filter { peopleIDs.contains($0.personID) }
|
||||
return PlanExchange(
|
||||
scope: scope,
|
||||
range: range,
|
||||
resources: ResourceBundle(
|
||||
churches: try churches(),
|
||||
people: relevantPeople,
|
||||
absences: relevantAbsences,
|
||||
templates: try templates(),
|
||||
exceptions: try exceptions()
|
||||
),
|
||||
services: services,
|
||||
assignments: assignments,
|
||||
liturgicalDays: scope == .resources ? [] : try liturgicalDays(in: range),
|
||||
note: "Export aus LektorenPlan · \(DayMath.key(range.start)) bis \(DayMath.key(range.end))"
|
||||
)
|
||||
}
|
||||
|
||||
public func applyPlanExchange(_ exchange: PlanExchange) throws -> ExchangeSummary {
|
||||
try database.transaction {
|
||||
for church in exchange.resources.churches { try upsert(church) }
|
||||
for person in exchange.resources.people { try upsert(person) }
|
||||
for absence in exchange.resources.absences { try upsert(absence) }
|
||||
for template in exchange.resources.templates { try upsert(template) }
|
||||
for exception in exchange.resources.exceptions { try upsert(exception) }
|
||||
for day in exchange.liturgicalDays { try upsert(liturgicalDay: day) }
|
||||
for service in exchange.services { try upsert(service) }
|
||||
for assignment in exchange.assignments { try upsert(assignment) }
|
||||
}
|
||||
return exchange.summary
|
||||
}
|
||||
|
||||
// MARK: - Utilities
|
||||
|
||||
private func encode<T: Encodable>(_ value: T) -> String {
|
||||
guard let data = try? encoder.encode(value) else { return "[]" }
|
||||
return String(data: data, encoding: .utf8) ?? "[]"
|
||||
}
|
||||
|
||||
private func decode<T: Decodable>(_ string: String) -> T {
|
||||
guard let data = string.data(using: .utf8),
|
||||
let value = try? decoder.decode(T.self, from: data)
|
||||
else {
|
||||
if T.self == [String].self { return [] as! T }
|
||||
if T.self == [Int].self { return [] as! T }
|
||||
return [] as! T
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
public func resetDemoData() throws {
|
||||
try database.execute("""
|
||||
DELETE FROM assignments; DELETE FROM services; DELETE FROM service_exceptions;
|
||||
DELETE FROM service_templates; DELETE FROM absences; DELETE FROM people;
|
||||
DELETE FROM churches; DELETE FROM liturgical_days;
|
||||
""")
|
||||
try DemoData.seed(into: self)
|
||||
}
|
||||
|
||||
public func databaseSizeBytes() -> Int {
|
||||
guard path != ":memory:" else { return 0 }
|
||||
let attributes = try? FileManager.default.attributesOfItem(atPath: path)
|
||||
return (attributes?[.size] as? NSNumber)?.intValue ?? 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
import Foundation
|
||||
|
||||
/// All app dates are "calendar days" anchored at noon in the Europe/Berlin time zone.
|
||||
/// Using noon avoids surprises around daylight-saving transitions while the ISO key
|
||||
/// remains stable for persistence.
|
||||
public enum DayMath {
|
||||
public static var calendar: Calendar {
|
||||
var cal = Calendar(identifier: .gregorian)
|
||||
cal.locale = Locale(identifier: "de_DE")
|
||||
cal.timeZone = TimeZone(identifier: "Europe/Berlin") ?? .current
|
||||
cal.firstWeekday = 2
|
||||
cal.minimumDaysInFirstWeek = 4
|
||||
return cal
|
||||
}
|
||||
|
||||
public static let germanLocale = Locale(identifier: "de_DE")
|
||||
|
||||
private static let keyFormatter: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.locale = Locale(identifier: "en_US_POSIX")
|
||||
f.timeZone = TimeZone(identifier: "Europe/Berlin")
|
||||
f.dateFormat = "yyyy-MM-dd"
|
||||
return f
|
||||
}()
|
||||
|
||||
private static let weekdayFormatter: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.locale = germanLocale
|
||||
f.timeZone = TimeZone(identifier: "Europe/Berlin")
|
||||
f.dateFormat = "EEEE"
|
||||
return f
|
||||
}()
|
||||
|
||||
private static let shortWeekdayFormatter: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.locale = germanLocale
|
||||
f.timeZone = TimeZone(identifier: "Europe/Berlin")
|
||||
f.dateFormat = "EEE"
|
||||
return f
|
||||
}()
|
||||
|
||||
private static let monthFormatter: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.locale = germanLocale
|
||||
f.timeZone = TimeZone(identifier: "Europe/Berlin")
|
||||
f.dateFormat = "MMMM"
|
||||
return f
|
||||
}()
|
||||
|
||||
private static let shortMonthFormatter: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.locale = germanLocale
|
||||
f.timeZone = TimeZone(identifier: "Europe/Berlin")
|
||||
f.dateFormat = "MMM"
|
||||
return f
|
||||
}()
|
||||
|
||||
private static let longFormatter: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.locale = germanLocale
|
||||
f.timeZone = TimeZone(identifier: "Europe/Berlin")
|
||||
f.dateFormat = "EEEE, d. MMMM yyyy"
|
||||
return f
|
||||
}()
|
||||
|
||||
private static let mediumFormatter: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.locale = germanLocale
|
||||
f.timeZone = TimeZone(identifier: "Europe/Berlin")
|
||||
f.dateFormat = "d. MMM yyyy"
|
||||
return f
|
||||
}()
|
||||
|
||||
public static func normalize(_ date: Date) -> Date {
|
||||
let comps = calendar.dateComponents([.year, .month, .day], from: date)
|
||||
return calendar.date(from: DateComponents(
|
||||
timeZone: calendar.timeZone,
|
||||
year: comps.year,
|
||||
month: comps.month,
|
||||
day: comps.day,
|
||||
hour: 12
|
||||
)) ?? date
|
||||
}
|
||||
|
||||
public static func today() -> Date {
|
||||
normalize(Date())
|
||||
}
|
||||
|
||||
public static func date(fromKey key: String) -> Date? {
|
||||
guard let date = keyFormatter.date(from: key) else { return nil }
|
||||
return normalize(date)
|
||||
}
|
||||
|
||||
public static func key(_ date: Date) -> String {
|
||||
keyFormatter.string(from: date)
|
||||
}
|
||||
|
||||
public static func key(year: Int, month: Int, day: Int) -> String {
|
||||
String(format: "%04d-%02d-%02d", year, month, day)
|
||||
}
|
||||
|
||||
public static func adding(days: Int, to date: Date) -> Date {
|
||||
calendar.date(byAdding: .day, value: days, to: normalize(date)) ?? date
|
||||
}
|
||||
|
||||
public static func adding(months: Int, to date: Date) -> Date {
|
||||
calendar.date(byAdding: .month, value: months, to: normalize(date)) ?? date
|
||||
}
|
||||
|
||||
public static func adding(years: Int, to date: Date) -> Date {
|
||||
calendar.date(byAdding: .year, value: years, to: normalize(date)) ?? date
|
||||
}
|
||||
|
||||
public static func daysBetween(_ start: Date, _ end: Date) -> Int {
|
||||
calendar.dateComponents([.day], from: normalize(start), to: normalize(end)).day ?? 0
|
||||
}
|
||||
|
||||
public static func days(in range: DayRange) -> [Date] {
|
||||
guard range.start <= range.end else { return [] }
|
||||
var result: [Date] = []
|
||||
var cursor = normalize(range.start)
|
||||
let end = normalize(range.end)
|
||||
while cursor <= end {
|
||||
result.append(cursor)
|
||||
cursor = adding(days: 1, to: cursor)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
public static func weekday(_ date: Date) -> Int {
|
||||
calendar.component(.weekday, from: normalize(date)) // 1 = Sunday … 7 = Saturday
|
||||
}
|
||||
|
||||
public static func isSunday(_ date: Date) -> Bool {
|
||||
weekday(date) == 1
|
||||
}
|
||||
|
||||
public static func isSaturday(_ date: Date) -> Bool {
|
||||
weekday(date) == 7
|
||||
}
|
||||
|
||||
public static func weekdayName(_ date: Date) -> String {
|
||||
weekdayFormatter.string(from: normalize(date))
|
||||
}
|
||||
|
||||
public static func shortWeekdayName(_ date: Date) -> String {
|
||||
shortWeekdayFormatter.string(from: normalize(date))
|
||||
}
|
||||
|
||||
public static func monthName(_ date: Date) -> String {
|
||||
monthFormatter.string(from: normalize(date))
|
||||
}
|
||||
|
||||
public static func shortMonthName(_ date: Date) -> String {
|
||||
shortMonthFormatter.string(from: normalize(date))
|
||||
}
|
||||
|
||||
public static func longString(_ date: Date) -> String {
|
||||
longFormatter.string(from: normalize(date))
|
||||
}
|
||||
|
||||
public static func mediumString(_ date: Date) -> String {
|
||||
mediumFormatter.string(from: normalize(date))
|
||||
}
|
||||
|
||||
public static func dayNumber(_ date: Date) -> Int {
|
||||
calendar.component(.day, from: normalize(date))
|
||||
}
|
||||
|
||||
public static func month(_ date: Date) -> Int {
|
||||
calendar.component(.month, from: normalize(date))
|
||||
}
|
||||
|
||||
public static func year(_ date: Date) -> Int {
|
||||
calendar.component(.year, from: normalize(date))
|
||||
}
|
||||
|
||||
public static func startOfYear(_ date: Date) -> Date {
|
||||
let y = year(date)
|
||||
return calendar.date(from: DateComponents(timeZone: calendar.timeZone, year: y, month: 1, day: 1, hour: 12)) ?? date
|
||||
}
|
||||
|
||||
public static func endOfYear(_ date: Date) -> Date {
|
||||
let y = year(date)
|
||||
return calendar.date(from: DateComponents(timeZone: calendar.timeZone, year: y, month: 12, day: 31, hour: 12)) ?? date
|
||||
}
|
||||
|
||||
public static func startOfMonth(_ date: Date) -> Date {
|
||||
let comps = calendar.dateComponents([.year, .month], from: date)
|
||||
return calendar.date(from: DateComponents(
|
||||
timeZone: calendar.timeZone, year: comps.year, month: comps.month, day: 1, hour: 12
|
||||
)) ?? date
|
||||
}
|
||||
|
||||
public static func endOfMonth(_ date: Date) -> Date {
|
||||
let start = startOfMonth(date)
|
||||
let next = adding(months: 1, to: start)
|
||||
return adding(days: -1, to: next)
|
||||
}
|
||||
|
||||
public static func startOfQuarter(_ date: Date) -> Date {
|
||||
let m = month(date)
|
||||
let quarterStartMonth = ((m - 1) / 3) * 3 + 1
|
||||
return calendar.date(from: DateComponents(
|
||||
timeZone: calendar.timeZone, year: year(date), month: quarterStartMonth, day: 1, hour: 12
|
||||
)) ?? date
|
||||
}
|
||||
|
||||
public static func endOfQuarter(_ date: Date) -> Date {
|
||||
adding(days: -1, to: adding(months: 3, to: startOfQuarter(date)))
|
||||
}
|
||||
|
||||
public static func quarter(_ date: Date) -> Int {
|
||||
(month(date) - 1) / 3 + 1
|
||||
}
|
||||
|
||||
public static func monthKey(_ date: Date) -> String {
|
||||
String(format: "%04d-%02d", year(date), month(date))
|
||||
}
|
||||
|
||||
public static func timeString(minutes: Int) -> String {
|
||||
let h = max(0, min(23, minutes / 60))
|
||||
let m = max(0, min(59, minutes % 60))
|
||||
return String(format: "%02d:%02d", h, m)
|
||||
}
|
||||
|
||||
public static func minutes(hour: Int, minute: Int) -> Int {
|
||||
hour * 60 + minute
|
||||
}
|
||||
|
||||
public static func ageString(from start: Date, to end: Date) -> String {
|
||||
let days = abs(daysBetween(start, end)) + 1
|
||||
return "\(days) Tage"
|
||||
}
|
||||
}
|
||||
|
||||
public struct DayRange: Hashable, Codable, Sendable, Identifiable {
|
||||
public var start: Date
|
||||
public var end: Date
|
||||
|
||||
public var id: String { "\(DayMath.key(start))_\(DayMath.key(end))" }
|
||||
|
||||
public init(start: Date, end: Date) {
|
||||
let a = DayMath.normalize(start)
|
||||
let b = DayMath.normalize(end)
|
||||
if a <= b {
|
||||
self.start = a
|
||||
self.end = b
|
||||
} else {
|
||||
self.start = b
|
||||
self.end = a
|
||||
}
|
||||
}
|
||||
|
||||
public init(startKey: String, endKey: String) {
|
||||
let start = DayMath.date(fromKey: startKey) ?? DayMath.today()
|
||||
let end = DayMath.date(fromKey: endKey) ?? start
|
||||
self.init(start: start, end: end)
|
||||
}
|
||||
|
||||
public static func quarter(containing date: Date) -> DayRange {
|
||||
DayRange(start: DayMath.startOfQuarter(date), end: DayMath.endOfQuarter(date))
|
||||
}
|
||||
|
||||
public static func year(_ year: Int) -> DayRange {
|
||||
let start = DayMath.date(fromKey: DayMath.key(year: year, month: 1, day: 1)) ?? DayMath.today()
|
||||
let end = DayMath.date(fromKey: DayMath.key(year: year, month: 12, day: 31)) ?? start
|
||||
return DayRange(start: start, end: end)
|
||||
}
|
||||
|
||||
public static func month(containing date: Date) -> DayRange {
|
||||
DayRange(start: DayMath.startOfMonth(date), end: DayMath.endOfMonth(date))
|
||||
}
|
||||
|
||||
public static func days(_ count: Int, from date: Date = DayMath.today()) -> DayRange {
|
||||
DayRange(start: date, end: DayMath.adding(days: max(0, count - 1), to: date))
|
||||
}
|
||||
|
||||
public var days: [Date] { DayMath.days(in: self) }
|
||||
|
||||
public var dayCount: Int { max(0, DayMath.daysBetween(start, end) + 1) }
|
||||
|
||||
public var monthCount: Int { max(1, (DayMath.year(end) - DayMath.year(start)) * 12 + DayMath.month(end) - DayMath.month(start) + 1) }
|
||||
|
||||
public var title: String {
|
||||
if DayMath.year(start) == DayMath.year(end) {
|
||||
return "\(DayMath.mediumString(start)) – \(DayMath.mediumString(end))"
|
||||
}
|
||||
return "\(DayMath.mediumString(start)) – \(DayMath.mediumString(end))"
|
||||
}
|
||||
|
||||
public var shortTitle: String {
|
||||
let startLabel = "\(DayMath.dayNumber(start)). \(DayMath.shortMonthName(start))"
|
||||
let endLabel = "\(DayMath.dayNumber(end)). \(DayMath.shortMonthName(end))"
|
||||
if DayMath.year(start) == DayMath.year(end) {
|
||||
return "\(startLabel) – \(endLabel) \(DayMath.year(end))"
|
||||
}
|
||||
return "\(startLabel) \(DayMath.year(start)) – \(endLabel) \(DayMath.year(end))"
|
||||
}
|
||||
|
||||
public func contains(_ date: Date) -> Bool {
|
||||
let d = DayMath.normalize(date)
|
||||
return d >= start && d <= end
|
||||
}
|
||||
|
||||
public func clamped(to bounds: DayRange) -> DayRange {
|
||||
DayRange(
|
||||
start: max(start, bounds.start),
|
||||
end: min(end, bounds.end)
|
||||
)
|
||||
}
|
||||
|
||||
public func extend(monthsBefore: Int, monthsAfter: Int) -> DayRange {
|
||||
DayRange(
|
||||
start: DayMath.adding(months: -monthsBefore, to: start),
|
||||
end: DayMath.adding(months: monthsAfter, to: end)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import Foundation
|
||||
|
||||
/// Seeds a realistic working dataset for the parish area of Bad Godesberg.
|
||||
/// All names, preferences and absences are fictional demo content.
|
||||
public enum DemoData {
|
||||
public static func seed(into db: AppDatabase) throws {
|
||||
let churches = makeChurches()
|
||||
for church in churches { try db.upsert(church) }
|
||||
|
||||
let people = makePeople()
|
||||
for person in people { try db.upsert(person) }
|
||||
for absence in makeAbsences() { try db.upsert(absence) }
|
||||
|
||||
let templates = makeTemplates()
|
||||
for template in templates { try db.upsert(template) }
|
||||
|
||||
if try db.liturgicalDayCount() == 0 {
|
||||
try db.upsert(liturgicalDays: LiturgicalSnapshot.loadBundled())
|
||||
}
|
||||
|
||||
try db.generateServices(in: DayRange.year(2025))
|
||||
try db.generateServices(in: DayRange.year(2026))
|
||||
try db.generateServices(in: DayRange.year(2027))
|
||||
try db.generateServices(in: DayRange.year(2028))
|
||||
|
||||
try addExceptions(to: db, templates: templates)
|
||||
try addSpecialServices(to: db)
|
||||
|
||||
// Demo history: everything before today is planned, the future is left open
|
||||
// so the planning workflow and the "offene Dienste" indicators are visible.
|
||||
let today = DayMath.today()
|
||||
let yesterday = DayMath.adding(days: -1, to: today)
|
||||
let pastRange = DayRange(
|
||||
start: DayMath.date(fromKey: "2025-01-01") ?? today,
|
||||
end: yesterday
|
||||
)
|
||||
let pastServices = try db.services(in: pastRange)
|
||||
let planner = ServicePlanner(
|
||||
people: people,
|
||||
absences: try db.absences(),
|
||||
services: pastServices,
|
||||
churches: churches,
|
||||
options: PlannerOptions(
|
||||
replaceExisting: true,
|
||||
respectPreferredWeekdays: true,
|
||||
weightFairness: 2.4,
|
||||
maxAssignmentsPerDay: 1
|
||||
)
|
||||
)
|
||||
let result = planner.plan()
|
||||
try db.savePlan(result.assignments, in: pastRange, replaceUnlocked: true)
|
||||
|
||||
// A few locked assignments demonstrate protected planning.
|
||||
let allAssignments = try db.assignments(in: pastRange)
|
||||
for (index, assignment) in allAssignments.enumerated() where index % 41 == 0 {
|
||||
try db.upsert(Assignment(
|
||||
id: assignment.id,
|
||||
serviceID: assignment.serviceID,
|
||||
personID: assignment.personID,
|
||||
role: assignment.role,
|
||||
locked: true,
|
||||
note: assignment.note,
|
||||
createdAt: assignment.createdAt
|
||||
))
|
||||
}
|
||||
|
||||
db.setSetting("demoSeededAt", value: ISO8601DateFormatter().string(from: Date()))
|
||||
db.setSetting("diocese", value: "koeln")
|
||||
if db.setting("autoSyncLiturgy") == nil {
|
||||
db.setSetting("autoSyncLiturgy", value: "1")
|
||||
}
|
||||
}
|
||||
|
||||
private static func makeChurches() -> [Church] {
|
||||
[
|
||||
Church(
|
||||
id: Church.andreasID,
|
||||
name: "St. Andreas",
|
||||
shortName: "Andreas",
|
||||
symbol: .basilica,
|
||||
colorHex: "#9B5B44",
|
||||
address: "Andreasstraße 1, 53179 Bonn",
|
||||
sortIndex: 0,
|
||||
notes: "Romanischer Kirchturm, Pfarrkirche im Rheinviertel"
|
||||
),
|
||||
Church(
|
||||
id: Church.evergislusID,
|
||||
name: "St. Evergislus",
|
||||
shortName: "Evergislus",
|
||||
symbol: .gothic,
|
||||
colorHex: "#4E6E5D",
|
||||
address: "Hardtstraße 13, 53175 Bonn",
|
||||
sortIndex: 1,
|
||||
notes: "Neugotische Kirche in Plittersdorf"
|
||||
),
|
||||
Church(
|
||||
id: Church.herzJesuID,
|
||||
name: "Herz Jesu",
|
||||
shortName: "Herz Jesu",
|
||||
symbol: .modern,
|
||||
colorHex: "#7A5A78",
|
||||
address: "Beethovenallee, 53173 Bonn",
|
||||
sortIndex: 2,
|
||||
notes: "Kirche im Villenviertel"
|
||||
),
|
||||
Church(
|
||||
id: Church.hildegardID,
|
||||
name: "St. Hildegard",
|
||||
shortName: "Hildegard",
|
||||
symbol: .rotunda,
|
||||
colorHex: "#B0833C",
|
||||
address: "Im Meisengarten, 53179 Bonn",
|
||||
sortIndex: 3,
|
||||
notes: "Rundkirche der 1960er Jahre in Rüngsdorf"
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
private static func makePeople() -> [Person] {
|
||||
[
|
||||
Person(id: "p-anna", firstName: "Anna", lastName: "Berg", roles: [.lector],
|
||||
email: "anna.berg@example.org", phone: "0228 555 0101",
|
||||
preferredChurchIDs: [Church.andreasID], preferredWeekdays: [1],
|
||||
preferredServiceTitles: ["Hochamt"], maxPerMonth: 7,
|
||||
notes: "Liest besonders gerne die Sonntagslesungen."),
|
||||
Person(id: "p-markus", firstName: "Markus", lastName: "Weber", roles: [.lector],
|
||||
email: "markus.weber@example.org", phone: "0228 555 0102",
|
||||
preferredChurchIDs: [Church.herzJesuID], preferredWeekdays: [1, 7],
|
||||
preferredServiceTitles: ["Vorabendmesse"], maxPerMonth: 8),
|
||||
Person(id: "p-elisabeth", firstName: "Elisabeth", lastName: "Klein", roles: [.lector, .helper],
|
||||
email: "elisabeth.klein@example.org", phone: "0228 555 0103",
|
||||
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 9,
|
||||
notes: "Flexibel einsetzbar, auch kurzfristig."),
|
||||
Person(id: "p-johannes", firstName: "Johannes", lastName: "Schmitz", roles: [.lector],
|
||||
email: "johannes.schmitz@example.org", preferredChurchIDs: [Church.evergislusID],
|
||||
preferredWeekdays: [1], preferredServiceTitles: ["Hochamt"], maxPerMonth: 6),
|
||||
Person(id: "p-maria", firstName: "Maria", lastName: "Hoffmann", roles: [.helper],
|
||||
preferredChurchIDs: [Church.herzJesuID], preferredWeekdays: [1], maxPerMonth: 8),
|
||||
Person(id: "p-peter", firstName: "Peter", lastName: "Lang", roles: [.helper],
|
||||
preferredChurchIDs: [Church.hildegardID], preferredWeekdays: [1], maxPerMonth: 6),
|
||||
Person(id: "p-susanne", firstName: "Susanne", lastName: "Vogel", roles: [.lector, .helper],
|
||||
preferredChurchIDs: [Church.andreasID], preferredWeekdays: [1], maxPerMonth: 8),
|
||||
Person(id: "p-thomas", firstName: "Thomas", lastName: "Neumann", roles: [.lector],
|
||||
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 10,
|
||||
notes: "Springerfunktion."),
|
||||
Person(id: "p-claudia", firstName: "Claudia", lastName: "Roth", roles: [.helper],
|
||||
preferredChurchIDs: [Church.evergislusID], preferredWeekdays: [1, 4], maxPerMonth: 7),
|
||||
Person(id: "p-michael", firstName: "Michael", lastName: "Braun", roles: [.helper],
|
||||
preferredChurchIDs: [Church.andreasID], preferredWeekdays: [1], maxPerMonth: 8),
|
||||
Person(id: "p-julia", firstName: "Julia", lastName: "Schröder", roles: [.lector, .helper],
|
||||
preferredChurchIDs: [Church.herzJesuID, Church.hildegardID], preferredWeekdays: [1, 7],
|
||||
maxPerMonth: 8),
|
||||
Person(id: "p-andreas", firstName: "Andreas", lastName: "Wolff", roles: [.lector],
|
||||
preferredChurchIDs: [Church.hildegardID], preferredWeekdays: [1],
|
||||
preferredServiceTitles: ["Wort-Gottes-Feier"], maxPerMonth: 6),
|
||||
Person(id: "p-birgit", firstName: "Birgit", lastName: "Sauer", roles: [.helper],
|
||||
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 9),
|
||||
Person(id: "p-daniel", firstName: "Daniel", lastName: "Krüger", roles: [.lector],
|
||||
preferredChurchIDs: [Church.herzJesuID, Church.andreasID], preferredWeekdays: [1, 2, 5],
|
||||
maxPerMonth: 7),
|
||||
Person(id: "p-petra", firstName: "Petra", lastName: "Sommer", roles: [.helper],
|
||||
preferredChurchIDs: [Church.evergislusID, Church.hildegardID], preferredWeekdays: [1, 7],
|
||||
maxPerMonth: 7),
|
||||
Person(id: "p-stefan", firstName: "Stefan", lastName: "Haas", roles: [.lector, .helper],
|
||||
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 9),
|
||||
Person(id: "p-monika", firstName: "Monika", lastName: "Albrecht", roles: [.helper],
|
||||
preferredChurchIDs: [Church.andreasID], preferredWeekdays: [1, 3], maxPerMonth: 6),
|
||||
Person(id: "p-christoph", firstName: "Christoph", lastName: "Mertens", roles: [.lector],
|
||||
preferredChurchIDs: [Church.evergislusID], preferredWeekdays: [1, 7],
|
||||
preferredServiceTitles: ["Vorabendmesse"], maxPerMonth: 7),
|
||||
Person(id: "p-simone", firstName: "Simone", lastName: "Becker", roles: [.helper],
|
||||
preferredChurchIDs: [], preferredWeekdays: [], maxPerMonth: 8),
|
||||
Person(id: "p-martin", firstName: "Martin", lastName: "Fuchs", roles: [.lector],
|
||||
preferredChurchIDs: [], preferredWeekdays: [1, 3], maxPerMonth: 7),
|
||||
Person(id: "p-ursula", firstName: "Ursula", lastName: "Peters", roles: [.helper],
|
||||
preferredChurchIDs: [], preferredWeekdays: [3, 4, 5], maxPerMonth: 8,
|
||||
notes: "Werktagsmessen."),
|
||||
Person(id: "p-frank", firstName: "Frank", lastName: "Lorenz", roles: [.lector],
|
||||
preferredChurchIDs: [], preferredWeekdays: [2, 3, 5], maxPerMonth: 8,
|
||||
notes: "Werktagsmessen.")
|
||||
]
|
||||
}
|
||||
|
||||
private static func makeAbsences() -> [Absence] {
|
||||
func date(_ key: String) -> Date { DayMath.date(fromKey: key) ?? DayMath.today() }
|
||||
return [
|
||||
Absence(personID: "p-anna", start: date("2026-12-20"), end: date("2027-01-06"), reason: "Weihnachtsreise"),
|
||||
Absence(personID: "p-markus", start: date("2026-11-10"), end: date("2026-11-24"), reason: "Kur"),
|
||||
Absence(personID: "p-maria", start: date("2027-03-01"), end: date("2027-03-15"), reason: "Fortbildung"),
|
||||
Absence(personID: "p-peter", start: date("2026-12-24"), end: date("2026-12-26"), reason: "Familie"),
|
||||
Absence(personID: "p-susanne", start: date("2026-08-01"), end: date("2026-08-21"), reason: "Urlaub"),
|
||||
Absence(personID: "p-michael", start: date("2026-11-01"), end: date("2026-11-08"), reason: "Urlaub"),
|
||||
Absence(personID: "p-julia", start: date("2027-05-01"), end: date("2027-05-14"), reason: "Urlaub"),
|
||||
Absence(personID: "p-birgit", start: date("2026-11-15"), end: date("2026-11-22"), reason: "Dienstreise"),
|
||||
Absence(personID: "p-daniel", start: date("2026-12-01"), end: date("2026-12-12"), reason: "Umzug"),
|
||||
Absence(personID: "p-petra", start: date("2027-02-01"), end: date("2027-02-14"), reason: "Winterurlaub"),
|
||||
Absence(personID: "p-thomas", start: date("2027-04-01"), end: date("2027-04-20"), reason: "Reha"),
|
||||
Absence(personID: "p-simone", start: date("2026-12-24"), end: date("2027-01-02"), reason: "Familienbesuch"),
|
||||
Absence(personID: "p-ursula", start: date("2026-09-07"), end: date("2026-09-20"), reason: "Urlaub"),
|
||||
Absence(personID: "p-frank", start: date("2026-11-23"), end: date("2026-12-04"), reason: "Kur")
|
||||
]
|
||||
}
|
||||
|
||||
private static func makeTemplates() -> [ServiceTemplate] {
|
||||
let from = DayMath.date(fromKey: "2024-01-01") ?? DayMath.today()
|
||||
func t(_ id: String, _ church: String, _ weekday: Int, _ hour: Int, _ minute: Int,
|
||||
_ title: String, _ lectors: Int = 1, _ helpers: Int = 1, notes: String = "") -> ServiceTemplate {
|
||||
ServiceTemplate(
|
||||
id: id,
|
||||
churchID: church,
|
||||
weekday: weekday,
|
||||
timeMinutes: DayMath.minutes(hour: hour, minute: minute),
|
||||
title: title,
|
||||
lectorsNeeded: lectors,
|
||||
helpersNeeded: helpers,
|
||||
validFrom: from,
|
||||
notes: notes
|
||||
)
|
||||
}
|
||||
return [
|
||||
t("t-andreas-so-hl", Church.andreasID, 1, 9, 30, "Hochamt", 1, 2, notes: "Sonntägliches Hochamt"),
|
||||
t("t-andreas-so-ab", Church.andreasID, 1, 18, 0, "Abendmesse", 1, 1),
|
||||
t("t-andreas-mi", Church.andreasID, 4, 8, 30, "Werktagsmesse", 1, 1),
|
||||
|
||||
t("t-evergislus-sa", Church.evergislusID, 7, 18, 0, "Vorabendmesse", 1, 1, notes: "Samstagabend"),
|
||||
t("t-evergislus-so", Church.evergislusID, 1, 11, 0, "Hochamt", 1, 2),
|
||||
t("t-evergislus-do", Church.evergislusID, 5, 8, 30, "Werktagsmesse", 1, 1),
|
||||
|
||||
t("t-herzjesu-sa", Church.herzJesuID, 7, 17, 0, "Vorabendmesse", 1, 1),
|
||||
t("t-herzjesu-so", Church.herzJesuID, 1, 10, 0, "Hochamt", 1, 2),
|
||||
t("t-herzjesu-di", Church.herzJesuID, 3, 18, 0, "Werktagsmesse", 1, 1),
|
||||
t("t-herzjesu-fr", Church.herzJesuID, 6, 8, 30, "Werktagsmesse", 1, 1),
|
||||
|
||||
t("t-hildegard-so", Church.hildegardID, 1, 9, 0, "Messe", 1, 1),
|
||||
t("t-hildegard-wgf", Church.hildegardID, 1, 11, 30, "Wort-Gottes-Feier", 1, 0, notes: "Lektorat, keine Kommunionspendung"),
|
||||
t("t-hildegard-mi", Church.hildegardID, 4, 18, 30, "Werktagsmesse", 1, 1)
|
||||
]
|
||||
}
|
||||
|
||||
private static func addExceptions(to db: AppDatabase, templates: [ServiceTemplate]) throws {
|
||||
let goodFridays = ["2025-04-18", "2026-04-03", "2027-03-26"]
|
||||
let christmasEves = ["2025-12-24", "2027-12-24"]
|
||||
for template in templates {
|
||||
if template.weekday == 6, template.churchID == Church.herzJesuID {
|
||||
for key in goodFridays {
|
||||
if let date = DayMath.date(fromKey: key) {
|
||||
try db.upsert(ServiceException(templateID: template.id, date: date, reason: "Karfreitag – keine Werktagsmesse"))
|
||||
}
|
||||
}
|
||||
}
|
||||
if template.weekday == 4 {
|
||||
for key in christmasEves {
|
||||
if let date = DayMath.date(fromKey: key) {
|
||||
try db.upsert(ServiceException(templateID: template.id, date: date, reason: "Heiliger Abend"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Holy Saturday: the Easter Vigil replaces the regular Saturday evening mass.
|
||||
if let evergislus = templates.first(where: { $0.id == "t-evergislus-sa" }) {
|
||||
for key in ["2025-04-19", "2026-04-04", "2027-03-27"] {
|
||||
if let date = DayMath.date(fromKey: key) {
|
||||
try db.upsert(ServiceException(templateID: evergislus.id, date: date, reason: "Osternacht"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func addSpecialServices(to db: AppDatabase) throws {
|
||||
func date(_ key: String) -> Date { DayMath.date(fromKey: key) ?? DayMath.today() }
|
||||
let specials: [ServiceOccurrence] = [
|
||||
ServiceOccurrence(churchID: Church.andreasID, date: date("2025-12-24"), timeMinutes: DayMath.minutes(hour: 16, minute: 0),
|
||||
title: "Familienchristmette", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
|
||||
notes: "Kinder- und Familienchristmette mit Krippenspiel"),
|
||||
ServiceOccurrence(churchID: Church.herzJesuID, date: date("2025-12-24"), timeMinutes: DayMath.minutes(hour: 22, minute: 0),
|
||||
title: "Christmette", lectorsNeeded: 1, helpersNeeded: 2, kind: .special),
|
||||
ServiceOccurrence(churchID: Church.evergislusID, date: date("2025-04-19"), timeMinutes: DayMath.minutes(hour: 21, minute: 0),
|
||||
title: "Osternacht", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
|
||||
notes: "Hochfest der Auferstehung, Lichterfeier"),
|
||||
|
||||
ServiceOccurrence(churchID: Church.andreasID, date: date("2026-04-04"), timeMinutes: DayMath.minutes(hour: 21, minute: 0),
|
||||
title: "Osternacht", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
|
||||
notes: "Lichterfeier mit Taufgedächtnis"),
|
||||
ServiceOccurrence(churchID: Church.andreasID, date: date("2026-11-30"), timeMinutes: DayMath.minutes(hour: 18, minute: 0),
|
||||
title: "Patronatsfest St. Andreas", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
|
||||
notes: "Hochfest des heiligen Andreas"),
|
||||
ServiceOccurrence(churchID: Church.andreasID, date: date("2026-12-24"), timeMinutes: DayMath.minutes(hour: 16, minute: 0),
|
||||
title: "Familienchristmette", lectorsNeeded: 1, helpersNeeded: 1, kind: .special,
|
||||
notes: "Kinder- und Familienchristmette"),
|
||||
ServiceOccurrence(churchID: Church.herzJesuID, date: date("2026-12-24"), timeMinutes: DayMath.minutes(hour: 22, minute: 0),
|
||||
title: "Christmette", lectorsNeeded: 1, helpersNeeded: 2, kind: .special),
|
||||
|
||||
ServiceOccurrence(churchID: Church.evergislusID, date: date("2027-03-27"), timeMinutes: DayMath.minutes(hour: 21, minute: 0),
|
||||
title: "Osternacht", lectorsNeeded: 1, helpersNeeded: 1, kind: .special),
|
||||
ServiceOccurrence(churchID: Church.herzJesuID, date: date("2027-06-04"), timeMinutes: DayMath.minutes(hour: 10, minute: 0),
|
||||
title: "Fronleichnamsprozession", lectorsNeeded: 1, helpersNeeded: 2, kind: .special,
|
||||
notes: "Gemeinsame Prozession der Pfarrgemeinschaft"),
|
||||
ServiceOccurrence(churchID: Church.andreasID, date: date("2027-12-24"), timeMinutes: DayMath.minutes(hour: 16, minute: 0),
|
||||
title: "Familienchristmette", lectorsNeeded: 1, helpersNeeded: 1, kind: .special),
|
||||
ServiceOccurrence(churchID: Church.herzJesuID, date: date("2027-12-24"), timeMinutes: DayMath.minutes(hour: 22, minute: 0),
|
||||
title: "Christmette", lectorsNeeded: 1, helpersNeeded: 2, kind: .special)
|
||||
]
|
||||
for service in specials { try db.upsert(service) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import Foundation
|
||||
|
||||
// MARK: - Bundled offline snapshot
|
||||
|
||||
private struct SnapshotFile: Decodable {
|
||||
struct Day: Decodable {
|
||||
let date: String
|
||||
let title: String
|
||||
let rank: String
|
||||
let color: String
|
||||
let bem: String
|
||||
let l1: String
|
||||
let ap: String
|
||||
let l2: String
|
||||
let ev: String
|
||||
let obligation: Bool
|
||||
}
|
||||
|
||||
let version: Int
|
||||
let source: String
|
||||
let diocese: String
|
||||
let years: [Int]
|
||||
let days: [Day]
|
||||
}
|
||||
|
||||
public enum LiturgicalSnapshot {
|
||||
public static let sourceLabel = "Daten von www.eucharistiefeier.de"
|
||||
|
||||
public static func loadBundled() -> [LiturgicalDay] {
|
||||
guard let url = bundledURL(),
|
||||
let data = try? Data(contentsOf: url),
|
||||
let file = try? JSONDecoder().decode(SnapshotFile.self, from: data)
|
||||
else {
|
||||
return []
|
||||
}
|
||||
return file.days.compactMap { day in
|
||||
guard let date = DayMath.date(fromKey: day.date) else { return nil }
|
||||
let rank = LiturgicalRank(rawValue: day.rank) ?? .weekday
|
||||
return LiturgicalDay(
|
||||
date: date,
|
||||
title: day.title,
|
||||
rank: rank,
|
||||
color: LiturgicalColor(apiValue: day.color),
|
||||
remark: day.bem,
|
||||
readings: Readings(first: day.l1, psalm: day.ap, second: day.l2, gospel: day.ev),
|
||||
isObligation: day.obligation,
|
||||
source: sourceLabel
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public static func bundledYears() -> [Int] {
|
||||
guard let url = bundledURL(),
|
||||
let data = try? Data(contentsOf: url),
|
||||
let file = try? JSONDecoder().decode(SnapshotFile.self, from: data)
|
||||
else { return [] }
|
||||
return file.years
|
||||
}
|
||||
|
||||
private static func bundledURL() -> URL? {
|
||||
let candidates: [URL?] = [
|
||||
Bundle.module.url(forResource: "liturgical-snapshot", withExtension: "json"),
|
||||
Bundle.main.url(forResource: "liturgical-snapshot", withExtension: "json"),
|
||||
Bundle.main.resourceURL?.appendingPathComponent("liturgical-snapshot.json")
|
||||
]
|
||||
return candidates.compactMap { $0 }.first { FileManager.default.fileExists(atPath: $0.path) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Live API
|
||||
|
||||
public enum LiturgicalAPIError: LocalizedError {
|
||||
case invalidURL
|
||||
case badStatus(Int)
|
||||
case invalidPayload(String)
|
||||
case emptyYear(Int)
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidURL:
|
||||
return "Die Kalender-URL konnte nicht erstellt werden."
|
||||
case .badStatus(let code):
|
||||
return "Der liturgische Kalender antwortete mit HTTP \(code)."
|
||||
case .invalidPayload(let detail):
|
||||
return "Die Kalenderdaten konnten nicht gelesen werden (\(detail))."
|
||||
case .emptyYear(let year):
|
||||
return "Für \(year) wurden keine liturgischen Daten geliefert."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public struct LiturgicalCalendarAPI: Sendable {
|
||||
public var diocese: String
|
||||
public var endpoint: URL
|
||||
|
||||
public init(diocese: String = "koeln", endpoint: URL = URL(string: "https://www.eucharistiefeier.de/lk/api.php")!) {
|
||||
self.diocese = diocese
|
||||
self.endpoint = endpoint
|
||||
}
|
||||
|
||||
public func fetch(year: Int) async throws -> [LiturgicalDay] {
|
||||
guard var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false) else {
|
||||
throw LiturgicalAPIError.invalidURL
|
||||
}
|
||||
components.queryItems = [
|
||||
URLQueryItem(name: "kal", value: diocese),
|
||||
URLQueryItem(name: "jahr", value: String(year)),
|
||||
URLQueryItem(name: "format", value: "json"),
|
||||
URLQueryItem(name: "info", value: "wdtrflu"),
|
||||
URLQueryItem(name: "dup", value: "e"),
|
||||
URLQueryItem(name: "bahn", value: "j")
|
||||
]
|
||||
guard let url = components.url else { throw LiturgicalAPIError.invalidURL }
|
||||
|
||||
var request = URLRequest(url: url)
|
||||
request.timeoutInterval = 45
|
||||
request.setValue("LektorenPlan/0.1 (macOS; Pfarrei Bad Godesberg)", forHTTPHeaderField: "User-Agent")
|
||||
request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
|
||||
|
||||
let (data, response) = try await URLSession.shared.data(for: request)
|
||||
if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
|
||||
throw LiturgicalAPIError.badStatus(http.statusCode)
|
||||
}
|
||||
return try Self.parse(data: data, year: year)
|
||||
}
|
||||
|
||||
public static func parse(data: Data, year: Int) throws -> [LiturgicalDay] {
|
||||
guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let celebrations = object["Zelebrationen"]
|
||||
else {
|
||||
throw LiturgicalAPIError.invalidPayload("Zelebrationen fehlen")
|
||||
}
|
||||
|
||||
var entries: [[String: Any]] = []
|
||||
if let dict = celebrations as? [String: Any] {
|
||||
entries = dict.values.compactMap { $0 as? [String: Any] }
|
||||
} else if let array = celebrations as? [[String: Any]] {
|
||||
entries = array
|
||||
}
|
||||
|
||||
let grouped = Dictionary(grouping: entries) { ($0["Datum"] as? String) ?? "" }
|
||||
var days: [LiturgicalDay] = []
|
||||
|
||||
for dateKey in grouped.keys.sorted() {
|
||||
guard dateKey.hasPrefix(String(year)), let date = DayMath.date(fromKey: dateKey) else { continue }
|
||||
let raw = grouped[dateKey] ?? []
|
||||
let valid = raw.filter { entry in
|
||||
let title = (entry["Tl"] as? String) ?? ""
|
||||
let remark = (entry["Bem"] as? String) ?? ""
|
||||
if title.contains("Bahnlesungen") { return false }
|
||||
if title.hasPrefix("Kommemoration") { return false }
|
||||
if title == "Weihe der eigenen Kirche" && remark.hasPrefix("Wenn") { return false }
|
||||
return true
|
||||
}
|
||||
guard !valid.isEmpty else { continue }
|
||||
|
||||
let best = valid.max { score($0, date: date) < score($1, date: date) } ?? valid[0]
|
||||
var readingEntry = best
|
||||
let bestTitle = (best["Tl"] as? String) ?? ""
|
||||
if ((best["L1"] as? String) ?? "").isEmpty && ((best["EV"] as? String) ?? "").isEmpty {
|
||||
readingEntry = valid.max {
|
||||
readingLength($0) < readingLength($1)
|
||||
} ?? best
|
||||
}
|
||||
|
||||
let title = bestTitle
|
||||
let rank = LiturgicalRank(rawValue: (best["Rang"] as? String) ?? "") ?? .weekday
|
||||
let colorValue = (best["Farbe"] as? String).flatMap { $0.isEmpty ? nil : $0 }
|
||||
?? (readingEntry["Farbe"] as? String)
|
||||
?? ""
|
||||
let readings = Readings(
|
||||
first: (readingEntry["L1"] as? String) ?? "",
|
||||
psalm: (readingEntry["AP"] as? String) ?? "",
|
||||
second: (readingEntry["L2"] as? String) ?? "",
|
||||
gospel: (readingEntry["EV"] as? String) ?? ""
|
||||
)
|
||||
days.append(LiturgicalDay(
|
||||
date: date,
|
||||
title: title,
|
||||
rank: rank,
|
||||
color: LiturgicalColor(apiValue: colorValue),
|
||||
remark: (best["Bem"] as? String) ?? "",
|
||||
readings: readings,
|
||||
isObligation: LiturgicalCalendarEngine.isObligation(date: date, title: title),
|
||||
source: LiturgicalSnapshot.sourceLabel
|
||||
))
|
||||
}
|
||||
|
||||
guard !days.isEmpty else { throw LiturgicalAPIError.emptyYear(year) }
|
||||
|
||||
// Complete gaps with the local calendar so a plan never has empty rows.
|
||||
let existing = Set(days.map(\.dateKey))
|
||||
let start = DayMath.date(fromKey: DayMath.key(year: year, month: 1, day: 1))!
|
||||
let end = DayMath.date(fromKey: DayMath.key(year: year, month: 12, day: 31))!
|
||||
for day in DayMath.days(in: DayRange(start: start, end: end)) where !existing.contains(DayMath.key(day)) {
|
||||
days.append(LiturgicalCalendarEngine.localDay(for: day))
|
||||
}
|
||||
|
||||
return days.sorted { $0.date < $1.date }
|
||||
}
|
||||
|
||||
private static func readingLength(_ entry: [String: Any]) -> Int {
|
||||
["L1", "AP", "L2", "EV"].reduce(0) { total, key in
|
||||
total + ((entry[key] as? String)?.count ?? 0)
|
||||
}
|
||||
}
|
||||
|
||||
private static func score(_ entry: [String: Any], date: Date) -> Int {
|
||||
var value = 0
|
||||
let rank = (entry["Rang"] as? String) ?? ""
|
||||
switch rank {
|
||||
case "H": value += 120
|
||||
case "F": value += 110
|
||||
case "G": value += 80
|
||||
case "g": value += 60
|
||||
default: value += 50
|
||||
}
|
||||
let title = (entry["Tl"] as? String) ?? ""
|
||||
let remark = (entry["Bem"] as? String) ?? ""
|
||||
let lowerTitle = title.lowercased()
|
||||
|
||||
if DayMath.isSunday(date) {
|
||||
if lowerTitle.contains("sonntag") || lowerTitle.contains("taufe des herrn") {
|
||||
value += 100
|
||||
}
|
||||
if rank.isEmpty { value += 30 }
|
||||
}
|
||||
if remark.contains("Am Tag") { value += 18 }
|
||||
else if remark.contains("Am Morgen") { value += 12 }
|
||||
else if remark.contains("Am Vorabend") { value -= 4 }
|
||||
else if remark.contains("In der Heiligen Nacht") { value += 5 }
|
||||
if remark.contains("Hochfest") { value += 10 }
|
||||
if title.range(of: #"^\d{1,2}\.\s"#, options: .regularExpression) != nil { value -= 25 }
|
||||
if !(((entry["L1"] as? String) ?? "").isEmpty && ((entry["EV"] as? String) ?? "").isEmpty) { value += 20 }
|
||||
if lowerTitle.contains("im jahreskreis") || lowerTitle.contains("osterzeit") { value += 5 }
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Combined loader
|
||||
|
||||
public enum LiturgicalData {
|
||||
/// Inserts the bundled snapshot when the database does not yet know these years.
|
||||
public static func bundledDays(notOlderThan existing: Set<String>) -> [LiturgicalDay] {
|
||||
LiturgicalSnapshot.loadBundled().filter { !existing.contains($0.dateKey) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
import Foundation
|
||||
|
||||
public enum LiturgicalCalendarEngine {
|
||||
// MARK: - Moveable feasts
|
||||
|
||||
public static func easterSunday(year: Int) -> Date {
|
||||
let a = year % 19
|
||||
let b = year / 100
|
||||
let c = year % 100
|
||||
let d = b / 4
|
||||
let e = b % 4
|
||||
let f = (b + 8) / 25
|
||||
let g = (b - f + 1) / 3
|
||||
let h = (19 * a + b - d - g + 15) % 30
|
||||
let i = c / 4
|
||||
let k = c % 4
|
||||
let l = (32 + 2 * e + 2 * i - h - k) % 7
|
||||
let m = (a + 11 * h + 22 * l) / 451
|
||||
let month = (h + l - 7 * m + 114) / 31
|
||||
let day = ((h + l - 7 * m + 114) % 31) + 1
|
||||
return DayMath.date(fromKey: DayMath.key(year: year, month: month, day: day)) ?? DayMath.today()
|
||||
}
|
||||
|
||||
public static func easterOffset(_ offset: Int, year: Int) -> Date {
|
||||
DayMath.adding(days: offset, to: easterSunday(year: year))
|
||||
}
|
||||
|
||||
public static func ashWednesday(year: Int) -> Date { easterOffset(-46, year: year) }
|
||||
public static func palmSunday(year: Int) -> Date { easterOffset(-7, year: year) }
|
||||
public static func holyThursday(year: Int) -> Date { easterOffset(-3, year: year) }
|
||||
public static func goodFriday(year: Int) -> Date { easterOffset(-2, year: year) }
|
||||
public static func holySaturday(year: Int) -> Date { easterOffset(-1, year: year) }
|
||||
public static func ascension(year: Int) -> Date { easterOffset(39, year: year) }
|
||||
public static func pentecost(year: Int) -> Date { easterOffset(49, year: year) }
|
||||
public static func corpusChristi(year: Int) -> Date { easterOffset(60, year: year) }
|
||||
public static func sacredHeart(year: Int) -> Date { easterOffset(68, year: year) }
|
||||
public static func trinitySunday(year: Int) -> Date { easterOffset(56, year: year) }
|
||||
|
||||
/// First Sunday of Advent (the Sunday between 27 November and 3 December).
|
||||
public static func adventStart(year: Int) -> Date {
|
||||
let christmasEve = DayMath.date(fromKey: DayMath.key(year: year, month: 12, day: 24)) ?? DayMath.today()
|
||||
var sunday = christmasEve
|
||||
while DayMath.weekday(sunday) != 1 {
|
||||
sunday = DayMath.adding(days: -1, to: sunday)
|
||||
}
|
||||
return DayMath.adding(days: -21, to: sunday)
|
||||
}
|
||||
|
||||
public static func christKing(year: Int) -> Date {
|
||||
DayMath.adding(days: -7, to: adventStart(year: year))
|
||||
}
|
||||
|
||||
public static func baptismOfTheLord(year: Int) -> Date {
|
||||
let epiphany = DayMath.date(fromKey: DayMath.key(year: year, month: 1, day: 6)) ?? DayMath.today()
|
||||
var sunday = DayMath.adding(days: 1, to: epiphany)
|
||||
while DayMath.weekday(sunday) != 1 {
|
||||
sunday = DayMath.adding(days: 1, to: sunday)
|
||||
}
|
||||
// If Epiphany itself falls on 7 or 8 January, the baptism is moved to the Monday.
|
||||
if DayMath.month(epiphany) == 1, DayMath.dayNumber(epiphany) >= 7 {
|
||||
return DayMath.adding(days: 1, to: epiphany)
|
||||
}
|
||||
return sunday
|
||||
}
|
||||
|
||||
// MARK: - Seasons
|
||||
|
||||
public static func season(for date: Date) -> LiturgicalSeason {
|
||||
let day = DayMath.normalize(date)
|
||||
let y = DayMath.year(day)
|
||||
let advent = adventStart(year: y)
|
||||
let christmas = DayMath.date(fromKey: DayMath.key(year: y, month: 12, day: 25)) ?? day
|
||||
let baptism = baptismOfTheLord(year: y)
|
||||
let ash = ashWednesday(year: y)
|
||||
let holyThursday = self.holyThursday(year: y)
|
||||
let easter = easterSunday(year: y)
|
||||
let pentecost = self.pentecost(year: y)
|
||||
|
||||
if day >= advent && day < christmas { return .advent }
|
||||
if day >= christmas || day <= baptism { return .christmas }
|
||||
if day >= ash && day < holyThursday { return .lent }
|
||||
if day >= easter && day <= pentecost { return .easter }
|
||||
if day > pentecost && day < advent { return .ordinary }
|
||||
return .ordinary
|
||||
}
|
||||
|
||||
public static func seasonName(for date: Date) -> String {
|
||||
season(for: date).title
|
||||
}
|
||||
|
||||
// MARK: - Obligation
|
||||
|
||||
public static func isObligation(date: Date, title: String = "") -> Bool {
|
||||
if DayMath.isSunday(date) { return true }
|
||||
let month = DayMath.month(date)
|
||||
let day = DayMath.dayNumber(date)
|
||||
switch (month, day) {
|
||||
case (1, 1), (1, 6), (8, 15), (11, 1), (12, 25):
|
||||
return true
|
||||
default:
|
||||
break
|
||||
}
|
||||
let lower = title.lowercased()
|
||||
if lower.contains("fronleichnam") { return true }
|
||||
if lower.contains("christi himmelfahrt") { return true }
|
||||
if lower.contains("pfingsten") && !lower.contains("vorabend") { return true }
|
||||
if lower.contains("ostersonntag") || lower.contains("osternacht") { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
// MARK: - Symbols
|
||||
|
||||
public static func symbol(for title: String, rank: LiturgicalRank, date: Date) -> FeastSymbol {
|
||||
let t = title.lowercased()
|
||||
if t.contains("weihnacht") || t.contains("geburt des herrn") { return .star }
|
||||
if t.contains("erscheinung") { return .star }
|
||||
if t.contains("ostern") || t.contains("auferstehung") { return .sun }
|
||||
if t.contains("pfingst") || t.contains("heiliger geist") { return .flame }
|
||||
if t.contains("fronleichnam") || t.contains("abendmahl") || t.contains("gründonnerstag") { return .candle }
|
||||
if t.contains("herz jesu") { return .heart }
|
||||
if t.contains("christkönig") { return .crown }
|
||||
if t.contains("allerheiligen") { return .crown }
|
||||
if t.contains("maria") || t.contains("mariä") { return .lily }
|
||||
if t.contains("kreuz") || t.contains("kreuzerhöhung") { return .cross }
|
||||
if t.contains("taufe") { return .dove }
|
||||
if t.contains("wort gottes") || t.contains("evangel") { return .book }
|
||||
if t.contains("lichtmess") || t.contains("darstellung") { return .candle }
|
||||
if t.contains("fronleichnam") { return .candle }
|
||||
if rank == .solemnity { return .cross }
|
||||
if rank == .feast { return .cross }
|
||||
return .book
|
||||
}
|
||||
|
||||
// MARK: - Local fallback
|
||||
|
||||
private static let fixedReadings: [String: Readings] = [
|
||||
"01-01": Readings(first: "Num 6, 22-27", psalm: "Ps 67 (66), 2-3.5.6 u. 8 (R: 2a)", second: "Gal 4, 4-7", gospel: "Lk 2, 16-21"),
|
||||
"01-06": Readings(first: "Jes 60, 1-6", psalm: "Ps 72 (71), 1-2.7-8.10-11.12-13 (R: 11)", second: "Eph 3, 2-3a.5-6", gospel: "Mt 2, 1-12"),
|
||||
"02-02": Readings(first: "Mal 3, 1-4", psalm: "Ps 24 (23), 7-8.9-10 (R: 8a)", second: "Hebr 2, 14-18", gospel: "Lk 2, 22-40"),
|
||||
"03-19": Readings(first: "2 Sam 7, 4-5a.12-14a.16", psalm: "Ps 89 (88), 2-3.4-5.27.29 (R: 37)", second: "Röm 4, 13.16-18.22", gospel: "Mt 1, 16.18-21.24a"),
|
||||
"03-25": Readings(first: "Jes 7, 10-14", psalm: "Ps 40 (39), 5-6.7-8a.8b-10 (R: 8a.9a)", second: "Hebr 10, 4-10", gospel: "Lk 1, 26-38"),
|
||||
"06-24": Readings(first: "Jes 49, 1-6", psalm: "Ps 139 (138), 1-3.13-14ab.14c-15 (R: 14a)", second: "Apg 13, 22-26", gospel: "Lk 1, 57-66.80"),
|
||||
"06-29": Readings(first: "Apg 12, 1-11", psalm: "Ps 34 (33), 2-3.4-5.6-7.8-9 (R: 5b)", second: "2 Tim 4, 6-8.17-18", gospel: "Mt 16, 13-19"),
|
||||
"08-15": Readings(first: "Offb 11, 19a; 12, 1-6a.10ab", psalm: "Ps 45 (44), 11-12.16-17 (R: 10b)", second: "1 Kor 15, 20-27", gospel: "Lk 1, 39-56"),
|
||||
"09-14": Readings(first: "Num 21, 4b-9", psalm: "Ps 78 (77), 1-2.34-35.36-37.38 (R: 7b)", second: "Phil 2, 6-11", gospel: "Joh 3, 13-17"),
|
||||
"11-01": Readings(first: "Offb 7, 2-4.9-14", psalm: "Ps 24 (23), 1-2.3-4.5-6 (R: vgl. 6)", second: "1 Joh 3, 1-3", gospel: "Mt 5, 1-12a"),
|
||||
"11-02": Readings(first: "Jes 25, 6a.7-9", psalm: "Ps 23 (22), 1-3a.3b-4.5.6 (R: 1)", second: "Röm 8, 14-23", gospel: "Mt 25, 31-46"),
|
||||
"12-08": Readings(first: "Gen 3, 9-15.20", psalm: "Ps 98 (97), 1.2-3ab.3cd-4 (R: 1a)", second: "Eph 1, 3-6.11-12", gospel: "Lk 1, 26-38"),
|
||||
"12-24": Readings(first: "2 Sam 7, 1-5.8b-12.14a.16", psalm: "Ps 89 (88), 2-3.20a u. 4-5.27 u. 29 (R: 2a)", second: "", gospel: "Lk 1, 67-79"),
|
||||
"12-25": Readings(first: "Jes 52, 7-10", psalm: "Ps 98 (97), 1.2-3b.3c-4.5-6 (R: vgl. 3cd)", second: "Hebr 1, 1-6", gospel: "Joh 1, 1-18"),
|
||||
"12-26": Readings(first: "Apg 6, 8-10; 7, 54-59", psalm: "Ps 31 (30), 3-4.6.8.17 (R: 6a)", second: "", gospel: "Mt 10, 17-22")
|
||||
]
|
||||
|
||||
private static let easterReadings: [Int: Readings] = [
|
||||
-46: Readings(first: "Joel 2, 12-18", psalm: "Ps 51 (50), 3-4.5-6a.12-13.14 u. 17 (R: vgl. 3a)", second: "2 Kor 5, 20 - 6, 2", gospel: "Mt 6, 1-6.16-18"),
|
||||
-7: Readings(first: "Jes 50, 4-7", psalm: "Ps 22 (21), 8-9.17-18a.19-20.23-24 (R: 2a)", second: "Phil 2, 6-11", gospel: "Mt 21, 1-11"),
|
||||
-3: Readings(first: "Ex 12, 1-8.11-14", psalm: "Ps 116 (115), 12-13.15-16bc.17-18 (R: vgl. 1 Kor 10, 16)", second: "1 Kor 11, 23-26", gospel: "Joh 13, 1-15"),
|
||||
-2: Readings(first: "Jes 52, 13 - 53, 12", psalm: "Ps 31 (30), 2 u. 6.12-13.15-16.17 u. 25 (R: Lk 23, 46)", second: "Hebr 4, 14-16; 5, 7-9", gospel: "Joh 18, 1 - 19, 42"),
|
||||
0: Readings(first: "Apg 10, 34a.37-43", psalm: "Ps 118 (117), 1-2.16-17.22-23 (R: vgl. 24)", second: "Kol 3, 1-4 oder 1 Kor 5, 6b-8", gospel: "Joh 20, 1-9"),
|
||||
39: Readings(first: "Apg 1, 1-11", psalm: "Ps 47 (46), 2-3.6-7.8-9 (R: 6)", second: "Eph 1, 17-23", gospel: "Mk 16, 15-20"),
|
||||
49: Readings(first: "Apg 2, 1-11", psalm: "Ps 104 (103), 1-2.24-25.29-30.31 u. 34 (R: vgl. 30)", second: "1 Kor 12, 3b-7.12-13", gospel: "Joh 20, 19-23"),
|
||||
56: Readings(first: "Spr 8, 22-31", psalm: "Ps 8, 4-5.6-7.8-9 (R: 2a)", second: "Röm 5, 1-5", gospel: "Joh 16, 12-15"),
|
||||
60: Readings(first: "Dtn 8, 2-3.14-16a", psalm: "Ps 147, 12-13.14-15.19-20 (R: 12a)", second: "1 Kor 10, 16-17", gospel: "Joh 6, 51-58"),
|
||||
68: Readings(first: "Hos 11, 1.3-4.8c-9", psalm: "Jes 12, 2-3.4bcd.5-6 (R: 3)", second: "Eph 3, 8-12.14-19", gospel: "Joh 19, 31-37")
|
||||
]
|
||||
|
||||
public static func localDay(for date: Date) -> LiturgicalDay {
|
||||
let day = DayMath.normalize(date)
|
||||
let y = DayMath.year(day)
|
||||
let m = DayMath.month(day)
|
||||
let d = DayMath.dayNumber(day)
|
||||
let key = String(format: "%02d-%02d", m, d)
|
||||
let weekday = DayMath.weekday(day)
|
||||
let easter = easterSunday(year: y)
|
||||
let offset = DayMath.daysBetween(easter, day)
|
||||
|
||||
var title = ""
|
||||
var rank: LiturgicalRank = .weekday
|
||||
var color: LiturgicalColor = .green
|
||||
var readings = Readings()
|
||||
var remark = ""
|
||||
|
||||
// Moveable celebrations take precedence over fixed ones.
|
||||
switch offset {
|
||||
case -46:
|
||||
title = "Aschermittwoch"; rank = .weekday; color = .violet
|
||||
readings = easterReadings[-46] ?? Readings()
|
||||
case -7:
|
||||
title = "Palmsonntag"; rank = .feast; color = .red
|
||||
readings = easterReadings[-7] ?? Readings()
|
||||
case -3:
|
||||
title = "Gründonnerstag"; rank = .solemnity; color = .white
|
||||
readings = easterReadings[-3] ?? Readings()
|
||||
case -2:
|
||||
title = "Karfreitag"; rank = .solemnity; color = .red
|
||||
readings = easterReadings[-2] ?? Readings()
|
||||
case -1:
|
||||
title = "Karsamstag"; rank = .weekday; color = .violet
|
||||
case 0:
|
||||
title = "Ostersonntag"; rank = .solemnity; color = .white
|
||||
readings = easterReadings[0] ?? Readings()
|
||||
remark = "Hochfest der Auferstehung des Herrn"
|
||||
case 1:
|
||||
title = "Ostermontag"; rank = .solemnity; color = .white
|
||||
readings = Readings(first: "Apg 2, 14.22-33", psalm: "Ps 16 (15), 1-2a u. 5.7-8.9-10.11 (R: 11a)", second: "", gospel: "Mt 28, 8-15")
|
||||
case 39:
|
||||
title = "Christi Himmelfahrt"; rank = .solemnity; color = .white
|
||||
readings = easterReadings[39] ?? Readings()
|
||||
case 49:
|
||||
title = "Pfingsten"; rank = .solemnity; color = .red
|
||||
readings = easterReadings[49] ?? Readings()
|
||||
remark = "Hochfest des Heiligen Geistes"
|
||||
case 50:
|
||||
title = "Pfingstmontag"; rank = .solemnity; color = .red
|
||||
readings = Readings(first: "Apg 10, 34a.37-43", psalm: "Ps 118 (117), 1-2.16-17.22-23 (R: vgl. 24)", second: "Kol 3, 1-4", gospel: "Joh 20, 1-9")
|
||||
case 56:
|
||||
title = "Dreifaltigkeitssonntag"; rank = .solemnity; color = .white
|
||||
readings = easterReadings[56] ?? Readings()
|
||||
case 60:
|
||||
title = "Fronleichnam"; rank = .solemnity; color = .white
|
||||
readings = easterReadings[60] ?? Readings()
|
||||
remark = "Hochfest des Leibes und Blutes Christi"
|
||||
case 68:
|
||||
title = "Heiligstes Herz Jesu"; rank = .solemnity; color = .white
|
||||
readings = easterReadings[68] ?? Readings()
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
if title.isEmpty {
|
||||
switch key {
|
||||
case "01-01": title = "Neujahr – Hochfest der Gottesmutter Maria"; rank = .solemnity; color = .white
|
||||
case "01-06": title = "Erscheinung des Herrn"; rank = .solemnity; color = .white
|
||||
case "02-02": title = "Darstellung des Herrn"; rank = .feast; color = .white
|
||||
case "03-19": title = "Hl. Josef, Bräutigam der Gottesmutter"; rank = .solemnity; color = .white
|
||||
case "03-25": title = "Verkündigung des Herrn"; rank = .solemnity; color = .white
|
||||
case "06-24": title = "Geburt Johannes' des Täufers"; rank = .solemnity; color = .white
|
||||
case "06-29": title = "Petrus und Paulus"; rank = .solemnity; color = .red
|
||||
case "08-15": title = "Mariä Aufnahme in den Himmel"; rank = .solemnity; color = .white
|
||||
case "09-14": title = "Kreuzerhöhung"; rank = .feast; color = .red
|
||||
case "11-01": title = "Allerheiligen"; rank = .solemnity; color = .white
|
||||
case "11-02": title = "Allerseelen"; rank = .weekday; color = .violet
|
||||
case "12-08": title = "Mariä Empfängnis"; rank = .solemnity; color = .white
|
||||
case "12-24": title = "Heiliger Abend"; rank = .weekday; color = .white
|
||||
case "12-25": title = "Weihnachten – Hochfest der Geburt des Herrn"; rank = .solemnity; color = .white
|
||||
case "12-26": title = "Hl. Stephanus"; rank = .feast; color = .red
|
||||
default: break
|
||||
}
|
||||
if let r = fixedReadings[key] { readings = r }
|
||||
}
|
||||
|
||||
if title.isEmpty {
|
||||
if weekday == 1 {
|
||||
title = sundayTitle(for: day)
|
||||
color = DayMath.weekday(day) == 1 ? .green : .green
|
||||
if let fest = seasonalSundayRank(for: day) {
|
||||
rank = fest
|
||||
}
|
||||
} else {
|
||||
title = weekdayTitle(for: day)
|
||||
if season(for: day) == .advent || season(for: day) == .lent {
|
||||
color = .violet
|
||||
} else if season(for: day) == .christmas || season(for: day) == .easter {
|
||||
color = .white
|
||||
} else {
|
||||
color = .green
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if rank == .solemnity { color = .white }
|
||||
if rank == .feast && color == .green { color = .red }
|
||||
|
||||
return LiturgicalDay(
|
||||
date: day,
|
||||
title: title,
|
||||
rank: rank,
|
||||
color: color,
|
||||
remark: remark,
|
||||
readings: readings,
|
||||
isObligation: isObligation(date: day, title: title),
|
||||
source: "lokale Berechnung"
|
||||
)
|
||||
}
|
||||
|
||||
public static func localDays(in range: DayRange) -> [LiturgicalDay] {
|
||||
DayMath.days(in: range).map(localDay(for:))
|
||||
}
|
||||
|
||||
private static func seasonalSundayRank(for day: Date) -> LiturgicalRank? {
|
||||
let season = season(for: day)
|
||||
if season == .advent || season == .christmas || season == .lent || season == .easter {
|
||||
if season == .lent && DayMath.daysBetween(palmSunday(year: DayMath.year(day)), day) == 0 {
|
||||
return .feast
|
||||
}
|
||||
return .weekday
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func sundayTitle(for day: Date) -> String {
|
||||
let y = DayMath.year(day)
|
||||
let season = season(for: day)
|
||||
switch season {
|
||||
case .advent:
|
||||
let start = adventStart(year: y)
|
||||
let index = DayMath.daysBetween(start, day) / 7 + 1
|
||||
return ["1. Adventssonntag", "2. Adventssonntag", "3. Adventssonntag", "4. Adventssonntag"].indices.contains(index - 1)
|
||||
? ["1. Adventssonntag", "2. Adventssonntag", "3. Adventssonntag", "4. Adventssonntag"][index - 1]
|
||||
: "Adventssonntag"
|
||||
case .christmas:
|
||||
let baptism = baptismOfTheLord(year: y)
|
||||
if DayMath.daysBetween(baptism, day) == 0 {
|
||||
return "Taufe des Herrn"
|
||||
}
|
||||
return "Sonntag in der Weihnachtszeit"
|
||||
case .lent:
|
||||
let ash = ashWednesday(year: y)
|
||||
let index = DayMath.daysBetween(ash, day) / 7 + 1
|
||||
if index >= 6 { return "Palmsonntag" }
|
||||
return "\(index). Fastensonntag"
|
||||
case .easter:
|
||||
let easter = easterSunday(year: y)
|
||||
let index = DayMath.daysBetween(easter, day) / 7 + 1
|
||||
if index == 1 { return "Ostersonntag" }
|
||||
if index == 8 { return "Pfingsten" }
|
||||
return "\(index). Sonntag der Osterzeit"
|
||||
case .ordinary:
|
||||
return "Sonntag im Jahreskreis"
|
||||
}
|
||||
}
|
||||
|
||||
private static func weekdayTitle(for day: Date) -> String {
|
||||
let name = DayMath.weekdayName(day)
|
||||
switch season(for: day) {
|
||||
case .advent:
|
||||
return "\(name) im Advent"
|
||||
case .christmas:
|
||||
return "\(name) in der Weihnachtszeit"
|
||||
case .lent:
|
||||
return "\(name) in der Fastenzeit"
|
||||
case .easter:
|
||||
return "\(name) in der Osterzeit"
|
||||
case .ordinary:
|
||||
return "\(name) im Jahreskreis"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,913 @@
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 struct Person: Identifiable, Codable, Hashable, Sendable {
|
||||
public var id: 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 preferredServiceTitles: [String]
|
||||
public var maxPerMonth: Int
|
||||
public var active: Bool
|
||||
public var notes: String
|
||||
|
||||
public init(
|
||||
id: String = UUID().uuidString,
|
||||
firstName: String,
|
||||
lastName: String,
|
||||
roles: Set<Role> = [.lector],
|
||||
email: String = "",
|
||||
phone: String = "",
|
||||
preferredChurchIDs: Set<String> = [],
|
||||
preferredWeekdays: Set<Int> = [],
|
||||
preferredServiceTitles: [String] = [],
|
||||
maxPerMonth: Int = 6,
|
||||
active: Bool = true,
|
||||
notes: String = ""
|
||||
) {
|
||||
self.id = id
|
||||
self.firstName = firstName
|
||||
self.lastName = lastName
|
||||
self.roles = roles
|
||||
self.email = email
|
||||
self.phone = phone
|
||||
self.preferredChurchIDs = preferredChurchIDs
|
||||
self.preferredWeekdays = preferredWeekdays
|
||||
self.preferredServiceTitles = preferredServiceTitles
|
||||
self.maxPerMonth = maxPerMonth
|
||||
self.active = active
|
||||
self.notes = 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)."
|
||||
}
|
||||
|
||||
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) }
|
||||
}
|
||||
|
||||
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
|
||||
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,
|
||||
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
|
||||
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 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 note: String
|
||||
public var createdAt: Date
|
||||
|
||||
public init(
|
||||
id: String = UUID().uuidString,
|
||||
serviceID: String,
|
||||
personID: String,
|
||||
role: Role,
|
||||
locked: Bool = false,
|
||||
note: String = "",
|
||||
createdAt: Date = Date()
|
||||
) {
|
||||
self.id = id
|
||||
self.serviceID = serviceID
|
||||
self.personID = personID
|
||||
self.role = role
|
||||
self.locked = locked
|
||||
self.note = note
|
||||
self.createdAt = createdAt
|
||||
}
|
||||
}
|
||||
|
||||
// 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 }
|
||||
}
|
||||
|
||||
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 allowDoubleRolesOnSameDay: Bool
|
||||
public var weightChurchPreference: Double
|
||||
public var weightServicePreference: Double
|
||||
public var weightFairness: Double
|
||||
public var maxAssignmentsPerDay: Int
|
||||
|
||||
public init(
|
||||
replaceExisting: Bool = false,
|
||||
respectPreferredWeekdays: Bool = true,
|
||||
allowDoubleRolesOnSameDay: Bool = false,
|
||||
weightChurchPreference: Double = 8,
|
||||
weightServicePreference: Double = 4,
|
||||
weightFairness: Double = 2.2,
|
||||
maxAssignmentsPerDay: Int = 1
|
||||
) {
|
||||
self.replaceExisting = replaceExisting
|
||||
self.respectPreferredWeekdays = respectPreferredWeekdays
|
||||
self.allowDoubleRolesOnSameDay = allowDoubleRolesOnSameDay
|
||||
self.weightChurchPreference = weightChurchPreference
|
||||
self.weightServicePreference = weightServicePreference
|
||||
self.weightFairness = weightFairness
|
||||
self.maxAssignmentsPerDay = maxAssignmentsPerDay
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import Foundation
|
||||
|
||||
public struct ServicePlanner {
|
||||
public var people: [Person]
|
||||
public var absences: [Absence]
|
||||
public var services: [ServiceOccurrence]
|
||||
public var existingAssignments: [Assignment]
|
||||
public var churches: [Church]
|
||||
public var options: PlannerOptions
|
||||
|
||||
public init(
|
||||
people: [Person],
|
||||
absences: [Absence],
|
||||
services: [ServiceOccurrence],
|
||||
existingAssignments: [Assignment] = [],
|
||||
churches: [Church] = [],
|
||||
options: PlannerOptions = PlannerOptions()
|
||||
) {
|
||||
self.people = people
|
||||
self.absences = absences
|
||||
self.services = services
|
||||
self.existingAssignments = existingAssignments
|
||||
self.churches = churches
|
||||
self.options = options
|
||||
}
|
||||
|
||||
public func plan() -> PlanResult {
|
||||
let activePeople = people.filter(\.active)
|
||||
let peopleByID = Dictionary(uniqueKeysWithValues: activePeople.map { ($0.id, $0) })
|
||||
let absencesByPerson = Dictionary(grouping: absences, by: \.personID)
|
||||
let churchNames = Dictionary(uniqueKeysWithValues: churches.map { ($0.id, $0.name) })
|
||||
|
||||
var working: [Assignment]
|
||||
if options.replaceExisting {
|
||||
working = existingAssignments.filter(\.locked)
|
||||
} else {
|
||||
working = existingAssignments
|
||||
}
|
||||
|
||||
var totalByPerson: [String: Int] = [:]
|
||||
var monthByPerson: [String: Int] = [:]
|
||||
var dayByPerson: [String: Int] = [:]
|
||||
var churchByPerson: [String: [String: Int]] = [:]
|
||||
var lastDateByPerson: [String: Date] = [:]
|
||||
|
||||
for assignment in working {
|
||||
guard let service = services.first(where: { $0.id == assignment.serviceID }) else { continue }
|
||||
let month = DayMath.monthKey(service.date)
|
||||
totalByPerson[assignment.personID, default: 0] += 1
|
||||
monthByPerson["\(assignment.personID)|\(month)", default: 0] += 1
|
||||
dayByPerson["\(assignment.personID)|\(service.dateKey)", default: 0] += 1
|
||||
churchByPerson[assignment.personID, default: [:]][service.churchID, default: 0] += 1
|
||||
let previous = lastDateByPerson[assignment.personID]
|
||||
if previous == nil || service.date > previous! {
|
||||
lastDateByPerson[assignment.personID] = service.date
|
||||
}
|
||||
}
|
||||
|
||||
let sortedServices = services.sorted {
|
||||
if $0.date != $1.date { return $0.date < $1.date }
|
||||
if $0.timeMinutes != $1.timeMinutes { return $0.timeMinutes < $1.timeMinutes }
|
||||
return $0.id < $1.id
|
||||
}
|
||||
|
||||
var unfilled: [UnfilledSlot] = []
|
||||
var newAssignments: [Assignment] = []
|
||||
|
||||
for service in sortedServices {
|
||||
for role in Role.allCases {
|
||||
let required = service.requiredCount(for: role)
|
||||
guard required > 0 else { continue }
|
||||
let existingForRole = working.filter { $0.serviceID == service.id && $0.role == role }.count
|
||||
if existingForRole >= required { continue }
|
||||
|
||||
for _ in existingForRole..<required {
|
||||
let alreadyAssigned = Set(working.filter { $0.serviceID == service.id }.map(\.personID))
|
||||
let result = bestCandidate(
|
||||
for: service,
|
||||
role: role,
|
||||
people: activePeople,
|
||||
peopleByID: peopleByID,
|
||||
absencesByPerson: absencesByPerson,
|
||||
totalByPerson: totalByPerson,
|
||||
monthByPerson: monthByPerson,
|
||||
dayByPerson: dayByPerson,
|
||||
churchByPerson: churchByPerson,
|
||||
lastDateByPerson: lastDateByPerson,
|
||||
alreadyAssigned: alreadyAssigned
|
||||
)
|
||||
switch result {
|
||||
case .success(let person):
|
||||
let assignment = Assignment(
|
||||
serviceID: service.id,
|
||||
personID: person.id,
|
||||
role: role
|
||||
)
|
||||
newAssignments.append(assignment)
|
||||
working.append(assignment)
|
||||
totalByPerson[person.id, default: 0] += 1
|
||||
monthByPerson["\(person.id)|\(DayMath.monthKey(service.date))", default: 0] += 1
|
||||
dayByPerson["\(person.id)|\(service.dateKey)", default: 0] += 1
|
||||
churchByPerson[person.id, default: [:]][service.churchID, default: 0] += 1
|
||||
lastDateByPerson[person.id] = service.date
|
||||
case .failure(let reason):
|
||||
unfilled.append(UnfilledSlot(
|
||||
service: service,
|
||||
churchName: churchNames[service.churchID] ?? "",
|
||||
role: role,
|
||||
reason: reason
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let filled = newAssignments.count
|
||||
let message: String
|
||||
if filled == 0 && unfilled.isEmpty {
|
||||
message = "Alle Dienste im Zeitraum sind bereits vollständig besetzt."
|
||||
} else if unfilled.isEmpty {
|
||||
message = "\(filled) Dienst\(filled == 1 ? "" : "e") erfolgreich besetzt. Alle Lücken geschlossen."
|
||||
} else {
|
||||
message = "\(filled) Dienst\(filled == 1 ? "" : "e") besetzt, \(unfilled.count) Lücke\(unfilled.count == 1 ? "" : "n") bleiben offen."
|
||||
}
|
||||
|
||||
if options.replaceExisting {
|
||||
let locked = working.filter(\.locked)
|
||||
let combined = locked + newAssignments
|
||||
return PlanResult(assignments: combined, unfilled: unfilled, filledCount: filled, message: message)
|
||||
}
|
||||
return PlanResult(assignments: working, unfilled: unfilled, filledCount: filled, message: message)
|
||||
}
|
||||
|
||||
private enum CandidateResult {
|
||||
case success(Person)
|
||||
case failure(String)
|
||||
}
|
||||
|
||||
private func bestCandidate(
|
||||
for service: ServiceOccurrence,
|
||||
role: Role,
|
||||
people: [Person],
|
||||
peopleByID: [String: Person],
|
||||
absencesByPerson: [String: [Absence]],
|
||||
totalByPerson: [String: Int],
|
||||
monthByPerson: [String: Int],
|
||||
dayByPerson: [String: Int],
|
||||
churchByPerson: [String: [String: Int]],
|
||||
lastDateByPerson: [String: Date],
|
||||
alreadyAssigned: Set<String>
|
||||
) -> CandidateResult {
|
||||
var candidates: [(Person, Double)] = []
|
||||
var blockedReasons: [String: Int] = [:]
|
||||
|
||||
for person in people where person.canFill(role) {
|
||||
guard !alreadyAssigned.contains(person.id) else {
|
||||
blockedReasons["bereits im Gottesdienst", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
if let absences = absencesByPerson[person.id], absences.contains(where: { $0.overlaps(service.date) }) {
|
||||
blockedReasons["abwesend", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
if options.respectPreferredWeekdays,
|
||||
!person.preferredWeekdays.isEmpty,
|
||||
!person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
|
||||
blockedReasons["Einsatztag passt nicht", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
let month = DayMath.monthKey(service.date)
|
||||
let usedThisMonth = monthByPerson["\(person.id)|\(month)", default: 0]
|
||||
if person.maxPerMonth > 0, usedThisMonth >= person.maxPerMonth {
|
||||
blockedReasons["Monatslimit erreicht", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
let usedThisDay = dayByPerson["\(person.id)|\(service.dateKey)", default: 0]
|
||||
if usedThisDay >= options.maxAssignmentsPerDay {
|
||||
blockedReasons["bereits an diesem Tag", default: 0] += 1
|
||||
continue
|
||||
}
|
||||
|
||||
var score = 10.0
|
||||
if person.preferredChurchIDs.contains(service.churchID) {
|
||||
score += options.weightChurchPreference
|
||||
}
|
||||
if !person.preferredChurchIDs.isEmpty && !person.preferredChurchIDs.contains(service.churchID) {
|
||||
score -= 1.5
|
||||
}
|
||||
if !person.preferredServiceTitles.isEmpty {
|
||||
let title = service.title.lowercased()
|
||||
for preference in person.preferredServiceTitles where !preference.isEmpty {
|
||||
if title.contains(preference.lowercased()) {
|
||||
score += options.weightServicePreference
|
||||
}
|
||||
}
|
||||
}
|
||||
if person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
|
||||
score += 3
|
||||
}
|
||||
let total = totalByPerson[person.id, default: 0]
|
||||
score -= Double(total) * options.weightFairness
|
||||
let churchCount = churchByPerson[person.id]?[service.churchID, default: 0] ?? 0
|
||||
score -= Double(churchCount) * 0.4
|
||||
if let last = lastDateByPerson[person.id] {
|
||||
let gap = DayMath.daysBetween(last, service.date)
|
||||
if gap >= 14 { score += 1.8 } else if gap >= 7 { score += 0.8 }
|
||||
} else {
|
||||
score += 2.5
|
||||
}
|
||||
score += stableTieBreak("\(person.id)|\(service.id)|\(role.rawValue)")
|
||||
|
||||
candidates.append((person, score))
|
||||
}
|
||||
|
||||
guard let best = candidates.max(by: { $0.1 < $1.1 }) else {
|
||||
let reason: String
|
||||
if blockedReasons.isEmpty {
|
||||
reason = "Keine geeignete Person mit Rolle \(role.title)"
|
||||
} else if let top = blockedReasons.max(by: { $0.value < $1.value }) {
|
||||
reason = "\(top.key) (\(top.value) ausgeschlossen)"
|
||||
} else {
|
||||
reason = "Keine geeignete Person"
|
||||
}
|
||||
return .failure(reason)
|
||||
}
|
||||
return .success(best.0)
|
||||
}
|
||||
|
||||
private func stableTieBreak(_ value: String) -> Double {
|
||||
var hash = 5381
|
||||
for byte in value.utf8 {
|
||||
hash = ((hash << 5) &+ hash) &+ Int(byte)
|
||||
}
|
||||
return Double(abs(hash % 997)) / 100_000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"source":"www.eucharistiefeier.de","diocese":"Erzbistum Köln","years":[2025,2026,2027,2028],"days":[{"date":"2025-01-01","title":"1. Januar - Neujahr","rank":"H","color":"w","bem":"Hochfest der Gottesmutter Maria","l1":"Num 6, 22-27","ap":"Ps 67 (66), 2-3.5.6 u. 8 (R: 2a)","l2":"Gal 4, 4-7","ev":"Lk 2, 16-21","obligation":true},{"date":"2025-01-02","title":"Hl. Basilius der Große (379) und hl. Gregor von Nazianz (um 390), Bischöfe, Kirchenlehrer","rank":"G","color":"w","bem":"","l1":"Eph 4, 1-7.11-13","ap":"Ps 23 (22), 1-3.4.5.6 (R: 1)","l2":"","ev":"Mt 23, 8-12","obligation":false},{"date":"2025-01-03","title":"Heiligster Name Jesu","rank":"g","color":"w","bem":"","l1":"Phil 2, 1-11","ap":"Ps 8, 4-5.6-7.8-9 (R: 2a)","l2":"","ev":"Lk 2, 21-24","obligation":false},{"date":"2025-01-04","title":"4. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 3, 7-10","ap":"Ps 98 (97), 1.7-8.9 (R: vgl. 3cd)","l2":"","ev":"Joh 1, 35-42","obligation":false},{"date":"2025-01-05","title":"2. Sonntag nach Weihnachten","rank":"","color":"w","bem":"","l1":"Sir 24, 1-2.8-12 (1-4.12-16)","ap":"Ps 147, 12-13.14-15.19-20 (R: Joh 1, 14)","l2":"Eph 1, 3-6.15-18","ev":"Joh 1, 1-18","obligation":true},{"date":"2025-01-06","title":"Erscheinung des Herrn","rank":"H","color":"w","bem":"","l1":"Jes 60, 1-6","ap":"Ps 72 (71), 1-2.7-8.10-11.12-13 (R: 11)","l2":"Eph 3, 2-3a.5-6","ev":"Mt 2, 1-12","obligation":true},{"date":"2025-01-07","title":"Hl. Raimund von Peñafort, Ordensgründer (1275)","rank":"g","color":"w","bem":"","l1":"2 Kor 5, 14-20","ap":"Ps 103 (102), 1-2.3-4.8-9.13-14.17-18a (R: 11)","l2":"","ev":"Lk 12, 35-40","obligation":false},{"date":"2025-01-08","title":"Hl. Severin, Mönch in Norikum (482)","rank":"g","color":"w","bem":"","l1":"Jak 2, 14-17","ap":"Ps 107 (106), 1-2a u. 3.4-5.6-7.8-9 (R: vgl. Spr 31, 20)","l2":"","ev":"Mt 25, 31-46","obligation":false},{"date":"2025-01-09","title":"9. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 4, 11-18","ap":"Ps 72 (71), 1-2.10-11.12-13 (R: 11)","l2":"","ev":"Mk 6, 45-52","obligation":false},{"date":"2025-01-10","title":"10. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 4, 19 - 5, 4","ap":"Ps 72 (71), 1-2.14 u. 15bc.17 (R: 11)","l2":"","ev":"Lk 4, 14-22a","obligation":false},{"date":"2025-01-11","title":"11. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 5, 5-13","ap":"Ps 147, 12-13.14-15.19-20 (R: 12a)","l2":"","ev":"Lk 5, 12-16","obligation":false},{"date":"2025-01-12","title":"Taufe des Herrn","rank":"F","color":"w","bem":"Sonntag nach dem 6. Januar","l1":"Jes 42, 5a.1-4.6-7 oder Jes 40, 1-5.9-11","ap":"Ps 29 (28), 1-2.3ac-4.3b u. 9b-10 (R: vgl. 11b) oder Ps 104 (103), 1-2.3-4.24-25.27-28.29-30 (R: 1ab)","l2":"Apg 10, 34-38 oder Tit 2, 11-14; 3, 4-7","ev":"Lk 3, 15-16.21-22","obligation":true},{"date":"2025-01-13","title":"Hl. Hilarius, Bischof von Poitiers, Kirchenlehrer (um 367)","rank":"g","color":"w","bem":"","l1":"1 Joh 2, 18-25","ap":"Ps 110 (109), 1-2.3.4-5 (R: 4b)","l2":"","ev":"Mt 5, 13-19","obligation":false},{"date":"2025-01-14","title":"Dienstag der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 2, 5-12","ap":"Ps 8, 2 u. 5.6-7.8-9 (R: vgl. 7)","l2":"","ev":"Mk 1, 21-28","obligation":false},{"date":"2025-01-15","title":"Mittwoch der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 2, 11-12.13c-18","ap":"Ps 105 (104), 1-2.3-4.6-7.8-9 (R: 7a.8a)","l2":"","ev":"Mk 1, 29-39","obligation":false},{"date":"2025-01-16","title":"Donnerstag der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 3, 7-14","ap":"Ps 95 (94), 6-7b.7c-9.10-11 (R: vgl. 7c.8a)","l2":"","ev":"Mk 1, 40-45","obligation":false},{"date":"2025-01-17","title":"Hl. Antonius, Mönchsvater in Ägypten (356)","rank":"G","color":"w","bem":"","l1":"Eph 6, 10-13.18","ap":"Ps 16 (15), 1-2 u. 5.7-8.9 u. 11 (R: vgl. 5a)","l2":"","ev":"Mt 19, 16-26","obligation":false},{"date":"2025-01-18","title":"Samstag der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 4, 12-16","ap":"Ps 19 (18B), 8.9.10.11 u. 15 (R: vgl. Joh 6, 63b)","l2":"","ev":"Mk 2, 13-17","obligation":false},{"date":"2025-01-19","title":"2. Sonntag im Jahreskreis","rank":"","color":"g","bem":"","l1":"Jes 62, 1-5","ap":"Ps 96 (95), 1-2.3-4.6-7.10 (R: vgl. 3a)","l2":"1 Kor 12, 4-11","ev":"Joh 2, 1-11","obligation":true},{"date":"2025-01-20","title":"Hl. Fabian, Papst, Märtyrer (250)","rank":"g","color":"r","bem":"","l1":"1 Petr 5, 1-4","ap":"Ps 40 (39), 2 u. 4ab.7-8.9-10 (R: vgl. 8a.9a)","l2":"","ev":"Joh 21, 1.15-17","obligation":false},{"date":"2025-01-21","title":"Hl. Agnes, Jungfrau, Märtyrin in Rom (304)","rank":"g","color":"r","bem":"","l1":"1 Kor 1, 26-31","ap":"Ps 23 (22), 1-3.4.5.6 (R: 1)","l2":"","ev":"Mt 13, 44-46","obligation":false},{"date":"2025-01-22","title":"Hl. Vinzenz, Diakon, Märtyrer in Spanien (304)","rank":"g","color":"r","bem":"","l1":"2 Kor 4, 7-15","ap":"Ps 34 (33), 2-3.4-5.6-7.8-9 (R: vgl. 5b)","l2":"","ev":"Mt 10, 17-22","obligatioLine truncated
|
||||
@@ -0,0 +1,221 @@
|
||||
import Foundation
|
||||
import SQLite3
|
||||
|
||||
private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
|
||||
|
||||
public enum SQLiteValue: Sendable, Hashable {
|
||||
case text(String)
|
||||
case int(Int)
|
||||
case double(Double)
|
||||
case null
|
||||
|
||||
public static func bool(_ value: Bool) -> SQLiteValue { .int(value ? 1 : 0) }
|
||||
public static func dateKey(_ date: Date) -> SQLiteValue { .text(DayMath.key(date)) }
|
||||
public static func optionalText(_ value: String?) -> SQLiteValue { value.map { .text($0) } ?? .null }
|
||||
}
|
||||
|
||||
public struct SQLiteRow: Sendable {
|
||||
public let values: [String: SQLiteValue]
|
||||
|
||||
public func string(_ key: String) -> String? {
|
||||
guard case .text(let value)? = values[key] else { return nil }
|
||||
return value
|
||||
}
|
||||
|
||||
public func string(_ key: String, default defaultValue: String) -> String {
|
||||
string(key) ?? defaultValue
|
||||
}
|
||||
|
||||
public func int(_ key: String) -> Int? {
|
||||
switch values[key] {
|
||||
case .int(let value): return value
|
||||
case .text(let value): return Int(value)
|
||||
case .double(let value): return Int(value)
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func int(_ key: String, default defaultValue: Int) -> Int {
|
||||
int(key) ?? defaultValue
|
||||
}
|
||||
|
||||
public func double(_ key: String) -> Double? {
|
||||
switch values[key] {
|
||||
case .double(let value): return value
|
||||
case .int(let value): return Double(value)
|
||||
case .text(let value): return Double(value)
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func bool(_ key: String, default defaultValue: Bool = false) -> Bool {
|
||||
guard let value = int(key) else { return defaultValue }
|
||||
return value != 0
|
||||
}
|
||||
|
||||
public func date(_ key: String) -> Date? {
|
||||
guard let raw = string(key) else { return nil }
|
||||
return DayMath.date(fromKey: raw)
|
||||
}
|
||||
}
|
||||
|
||||
public struct SQLiteError: LocalizedError {
|
||||
public var message: String
|
||||
public var code: Int32
|
||||
|
||||
public var errorDescription: String? { "SQLite \(code): \(message)" }
|
||||
}
|
||||
|
||||
public final class SQLiteDatabase {
|
||||
private var handle: OpaquePointer?
|
||||
private let lock = NSRecursiveLock()
|
||||
public let path: String
|
||||
|
||||
public init(path: String) throws {
|
||||
self.path = path
|
||||
var db: OpaquePointer?
|
||||
let flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX
|
||||
let result = sqlite3_open_v2(path, &db, flags, nil)
|
||||
guard result == SQLITE_OK, let db else {
|
||||
let message = db.map { String(cString: sqlite3_errmsg($0)) } ?? "Unbekannter Fehler"
|
||||
if let db { sqlite3_close(db) }
|
||||
throw SQLiteError(message: message, code: result)
|
||||
}
|
||||
self.handle = db
|
||||
sqlite3_busy_timeout(db, 5_000)
|
||||
if path != ":memory:" {
|
||||
try execute("PRAGMA journal_mode=WAL;")
|
||||
}
|
||||
try execute("PRAGMA foreign_keys=ON;")
|
||||
try execute("PRAGMA synchronous=NORMAL;")
|
||||
}
|
||||
|
||||
deinit {
|
||||
if let handle {
|
||||
sqlite3_close(handle)
|
||||
}
|
||||
}
|
||||
|
||||
public func execute(_ sql: String) throws {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
guard let handle else { throw SQLiteError(message: "Datenbank geschlossen", code: SQLITE_MISUSE) }
|
||||
var errorMessage: UnsafeMutablePointer<CChar>?
|
||||
let result = sqlite3_exec(handle, sql, nil, nil, &errorMessage)
|
||||
if result != SQLITE_OK {
|
||||
let message = errorMessage.map { String(cString: $0) } ?? "Unbekannter Fehler"
|
||||
sqlite3_free(errorMessage)
|
||||
throw SQLiteError(message: message, code: result)
|
||||
}
|
||||
}
|
||||
|
||||
public func run(_ sql: String, _ params: [SQLiteValue] = []) throws {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
let statement = try prepare(sql)
|
||||
defer { sqlite3_finalize(statement) }
|
||||
try bind(params, to: statement)
|
||||
let result = sqlite3_step(statement)
|
||||
guard result == SQLITE_DONE || result == SQLITE_ROW else {
|
||||
throw currentError(code: result)
|
||||
}
|
||||
}
|
||||
|
||||
public func query(_ sql: String, _ params: [SQLiteValue] = []) throws -> [SQLiteRow] {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
let statement = try prepare(sql)
|
||||
defer { sqlite3_finalize(statement) }
|
||||
try bind(params, to: statement)
|
||||
|
||||
var rows: [SQLiteRow] = []
|
||||
while true {
|
||||
let result = sqlite3_step(statement)
|
||||
if result == SQLITE_DONE { break }
|
||||
guard result == SQLITE_ROW else { throw currentError(code: result) }
|
||||
|
||||
var values: [String: SQLiteValue] = [:]
|
||||
for index in 0..<sqlite3_column_count(statement) {
|
||||
let name = String(cString: sqlite3_column_name(statement, index))
|
||||
switch sqlite3_column_type(statement, index) {
|
||||
case SQLITE_INTEGER:
|
||||
values[name] = .int(Int(sqlite3_column_int64(statement, index)))
|
||||
case SQLITE_FLOAT:
|
||||
values[name] = .double(sqlite3_column_double(statement, index))
|
||||
case SQLITE_TEXT:
|
||||
if let text = sqlite3_column_text(statement, index) {
|
||||
values[name] = .text(String(cString: text))
|
||||
} else {
|
||||
values[name] = .null
|
||||
}
|
||||
default:
|
||||
values[name] = .null
|
||||
}
|
||||
}
|
||||
rows.append(SQLiteRow(values: values))
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
public func scalarInt(_ sql: String, _ params: [SQLiteValue] = []) throws -> Int {
|
||||
guard let row = try query(sql, params).first else { return 0 }
|
||||
if let value = row.int("value") { return value }
|
||||
guard case .int(let first)? = row.values.values.first else { return 0 }
|
||||
return first
|
||||
}
|
||||
|
||||
public var lastInsertRowID: Int64 {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
guard let handle else { return 0 }
|
||||
return sqlite3_last_insert_rowid(handle)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func transaction<T>(_ body: () throws -> T) throws -> T {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
try execute("BEGIN IMMEDIATE;")
|
||||
do {
|
||||
let value = try body()
|
||||
try execute("COMMIT;")
|
||||
return value
|
||||
} catch {
|
||||
try? execute("ROLLBACK;")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func prepare(_ sql: String) throws -> OpaquePointer {
|
||||
guard let handle else { throw SQLiteError(message: "Datenbank geschlossen", code: SQLITE_MISUSE) }
|
||||
var statement: OpaquePointer?
|
||||
let result = sqlite3_prepare_v2(handle, sql, -1, &statement, nil)
|
||||
guard result == SQLITE_OK, let statement else {
|
||||
throw currentError(code: result)
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
private func bind(_ params: [SQLiteValue], to statement: OpaquePointer) throws {
|
||||
for (offset, value) in params.enumerated() {
|
||||
let index = Int32(offset + 1)
|
||||
let result: Int32
|
||||
switch value {
|
||||
case .text(let string):
|
||||
result = sqlite3_bind_text(statement, index, string, -1, SQLITE_TRANSIENT)
|
||||
case .int(let int):
|
||||
result = sqlite3_bind_int64(statement, index, Int64(int))
|
||||
case .double(let double):
|
||||
result = sqlite3_bind_double(statement, index, double)
|
||||
case .null:
|
||||
result = sqlite3_bind_null(statement, index)
|
||||
}
|
||||
guard result == SQLITE_OK else { throw currentError(code: result) }
|
||||
}
|
||||
}
|
||||
|
||||
private func currentError(code: Int32) -> SQLiteError {
|
||||
let message = handle.map { String(cString: sqlite3_errmsg($0)) } ?? "Unbekannter Fehler"
|
||||
return SQLiteError(message: message, code: code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import Foundation
|
||||
|
||||
public enum StatisticsCalculator {
|
||||
public static func compute(
|
||||
range: DayRange,
|
||||
services: [ServiceOccurrence],
|
||||
assignments: [Assignment],
|
||||
people: [Person],
|
||||
churches: [Church],
|
||||
absences: [Absence] = []
|
||||
) -> RangeStatistics {
|
||||
let servicesByID = Dictionary(uniqueKeysWithValues: services.map { ($0.id, $0) })
|
||||
let peopleByID = Dictionary(uniqueKeysWithValues: people.map { ($0.id, $0) })
|
||||
let assignmentsByPerson = Dictionary(grouping: assignments, by: \.personID)
|
||||
let assignmentsByService = Dictionary(grouping: assignments, by: \.serviceID)
|
||||
|
||||
var personStats: [PersonStat] = people.map { person in
|
||||
let own = assignmentsByPerson[person.id] ?? []
|
||||
var lectors = 0
|
||||
var helpers = 0
|
||||
var churchCounts: [String: Int] = [:]
|
||||
var preferredHits = 0
|
||||
var sundays = 0
|
||||
var lastDate: Date?
|
||||
|
||||
for assignment in own {
|
||||
guard let service = servicesByID[assignment.serviceID] else { continue }
|
||||
if assignment.role == .lector { lectors += 1 } else { helpers += 1 }
|
||||
churchCounts[service.churchID, default: 0] += 1
|
||||
if DayMath.isSunday(service.date) { sundays += 1 }
|
||||
if lastDate == nil || service.date > lastDate! { lastDate = service.date }
|
||||
if preferenceHit(person: person, service: service) { preferredHits += 1 }
|
||||
}
|
||||
|
||||
return PersonStat(
|
||||
person: person,
|
||||
total: own.count,
|
||||
lectors: lectors,
|
||||
helpers: helpers,
|
||||
churchCounts: churchCounts,
|
||||
preferredHits: preferredHits,
|
||||
sundayCount: sundays,
|
||||
lastAssignment: lastDate
|
||||
)
|
||||
}
|
||||
personStats.sort {
|
||||
if $0.total != $1.total { return $0.total > $1.total }
|
||||
return $0.person.lastName < $1.person.lastName
|
||||
}
|
||||
|
||||
var churchStats: [ChurchStat] = churches.map { church in
|
||||
let churchServices = services.filter { $0.churchID == church.id }
|
||||
let serviceIDs = Set(churchServices.map(\.id))
|
||||
let churchAssignments = assignments.filter { serviceIDs.contains($0.serviceID) }
|
||||
let open = churchServices.reduce(0) { partial, service in
|
||||
partial + max(0, service.requiredSlots - (assignmentsByService[service.id]?.count ?? 0))
|
||||
}
|
||||
return ChurchStat(
|
||||
church: church,
|
||||
assignments: churchAssignments.count,
|
||||
services: churchServices.count,
|
||||
openSlots: open,
|
||||
personCount: Set(churchAssignments.map(\.personID)).count
|
||||
)
|
||||
}
|
||||
churchStats.sort { $0.church.sortIndex < $1.church.sortIndex }
|
||||
|
||||
var monthly: [String: Int] = [:]
|
||||
for assignment in assignments {
|
||||
guard let service = servicesByID[assignment.serviceID] else { continue }
|
||||
monthly[DayMath.monthKey(service.date), default: 0] += 1
|
||||
}
|
||||
|
||||
let sundayServices = services.filter { DayMath.isSunday($0.date) }
|
||||
let sundayServiceIDs = Set(sundayServices.map(\.id))
|
||||
let sundayFilled = assignments.filter { sundayServiceIDs.contains($0.serviceID) }.count
|
||||
let requiredSlots = services.reduce(0) { $0 + $1.requiredSlots }
|
||||
let openSlots = max(0, requiredSlots - assignments.count)
|
||||
|
||||
var preferenceHits = 0
|
||||
var preferenceEligible = 0
|
||||
for assignment in assignments {
|
||||
guard let service = servicesByID[assignment.serviceID],
|
||||
let person = peopleByID[assignment.personID] else { continue }
|
||||
if hasAnyPreference(person) {
|
||||
preferenceEligible += 1
|
||||
if preferenceHit(person: person, service: service) { preferenceHits += 1 }
|
||||
}
|
||||
}
|
||||
|
||||
let activePeople = Set(people.filter(\.active).map(\.id))
|
||||
var absenceDays = 0
|
||||
for absence in absences where activePeople.contains(absence.personID) {
|
||||
let clamped = absence.range.clamped(to: range)
|
||||
if clamped.start <= clamped.end { absenceDays += clamped.dayCount }
|
||||
}
|
||||
|
||||
return RangeStatistics(
|
||||
range: range,
|
||||
serviceCount: services.count,
|
||||
assignmentCount: assignments.count,
|
||||
openSlots: openSlots,
|
||||
requiredSlots: requiredSlots,
|
||||
personStats: personStats,
|
||||
churchStats: churchStats,
|
||||
monthlyCounts: monthly,
|
||||
sundayServiceCount: sundayServices.count,
|
||||
sundayFilled: sundayFilled,
|
||||
preferenceHits: preferenceHits,
|
||||
preferenceEligible: preferenceEligible,
|
||||
absenceDays: absenceDays
|
||||
)
|
||||
}
|
||||
|
||||
public static func hasAnyPreference(_ person: Person) -> Bool {
|
||||
!person.preferredChurchIDs.isEmpty || !person.preferredWeekdays.isEmpty || !person.preferredServiceTitles.isEmpty
|
||||
}
|
||||
|
||||
public static func preferenceHit(person: Person, service: ServiceOccurrence) -> Bool {
|
||||
if person.preferredChurchIDs.contains(service.churchID) { return true }
|
||||
if person.preferredWeekdays.contains(DayMath.weekday(service.date)) { return true }
|
||||
let title = service.title.lowercased()
|
||||
for preference in person.preferredServiceTitles where !preference.isEmpty {
|
||||
if title.contains(preference.lowercased()) { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
public static func candidateReasons(
|
||||
person: Person,
|
||||
service: ServiceOccurrence,
|
||||
absences: [Absence],
|
||||
assignments: [Assignment]
|
||||
) -> [String] {
|
||||
var reasons: [String] = []
|
||||
if !person.active { reasons.append("inaktiv") }
|
||||
if !person.canFill(.lector) && !person.canFill(.helper) { reasons.append("keine Rolle") }
|
||||
if absences.contains(where: { $0.personID == person.id && $0.overlaps(service.date) }) {
|
||||
reasons.append("abwesend")
|
||||
}
|
||||
if !person.preferredWeekdays.isEmpty && !person.preferredWeekdays.contains(DayMath.weekday(service.date)) {
|
||||
reasons.append("Einsatztag passt nicht")
|
||||
}
|
||||
if assignments.contains(where: { $0.serviceID == service.id && $0.personID == person.id }) {
|
||||
reasons.append("bereits eingeteilt")
|
||||
}
|
||||
return reasons
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user