UI verbessert, 2. PDF als kompakte Variante

This commit is contained in:
concierge committed 2026-11-12 19:59:51 +01:00
1 parent 1bf3283029
commit f9e3e94629
23 files changed
+1009 -146

No files matched your search

+44 -11
View File
@@ -10,7 +10,11 @@ public final class AppDatabase {
self.path = path
self.database = try SQLiteDatabase(path: path)
try migrate()
if seedDemo, try churchCount() == 0 {
// Only seed on a genuinely fresh install. After the user explicitly
// deletes all data we persist a marker so demo data does not reappear.
if seedDemo,
try churchCount() == 0,
setting("suppressDemoSeed") != "1" {
try DemoData.seed(into: self)
}
}
@@ -91,6 +95,7 @@ public final class AppDatabase {
CREATE TABLE IF NOT EXISTS services (
id TEXT PRIMARY KEY,
church_id TEXT NOT NULL REFERENCES churches(id) ON DELETE CASCADE,
location TEXT NOT NULL DEFAULT '',
template_id TEXT REFERENCES service_templates(id) ON DELETE SET NULL,
date TEXT NOT NULL,
time_minutes INTEGER NOT NULL,
@@ -142,7 +147,19 @@ public final class AppDatabase {
);
"""
try database.execute(schema)
try database.run("INSERT OR IGNORE INTO settings(key, value) VALUES('schemaVersion', '1')")
// Older databases predate the free-text location for special services.
try addColumnIfMissing(
table: "services",
column: "location",
definition: "TEXT NOT NULL DEFAULT ''"
)
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('schemaVersion', '2')")
}
private func addColumnIfMissing(table: String, column: String, definition: String) throws {
let columns = try database.query("PRAGMA table_info(\(table))")
guard !columns.contains(where: { $0.string("name") == column }) else { return }
try database.execute("ALTER TABLE \(table) ADD COLUMN \(column) \(definition);")
}
// MARK: - Churches
@@ -375,15 +392,17 @@ public final class AppDatabase {
public func upsert(_ service: ServiceOccurrence) throws {
try database.run("""
INSERT INTO services(id, church_id, template_id, date, time_minutes, title, lectors_needed,
INSERT INTO services(id, church_id, location, 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,
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET church_id=excluded.church_id, location=excluded.location,
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,
.text(service.id), .text(service.churchID), .text(service.location ?? ""),
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))
@@ -401,6 +420,7 @@ public final class AppDatabase {
return ServiceOccurrence(
id: id,
churchID: churchID,
location: row.string("location", default: ""),
templateID: row.string("template_id"),
date: date,
timeMinutes: row.int("time_minutes", default: 600),
@@ -739,12 +759,25 @@ public final class AppDatabase {
return value
}
/// Removes all content while keeping application settings (range, preferences).
/// By default a marker is stored so the demo dataset is not re-seeded on the
/// next launch; resetting the demo clears that marker again.
public func deleteAllData(markDemoSuppressed: Bool = true) throws {
try database.transaction {
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;
""")
if markDemoSuppressed {
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('suppressDemoSeed', '1')")
}
}
}
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 deleteAllData(markDemoSuppressed: false)
try database.run("DELETE FROM settings WHERE key='suppressDemoSeed'")
try DemoData.seed(into: self)
}
+5
View File
@@ -284,6 +284,11 @@ public enum DemoData {
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.herzJesuID, location: "Open-Air auf dem Theaterplatz",
date: date("2026-06-04"), timeMinutes: DayMath.minutes(hour: 10, minute: 0),
title: "Fronleichnamsmesse",
lectorsNeeded: 1, helpersNeeded: 2, kind: .special,
notes: "Gemeinsame Messfeier der Pfarreiengemeinschaft im Freien"),
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"),
+1 -1
View File
@@ -114,7 +114,7 @@ public struct LiturgicalCalendarAPI: Sendable {
var request = URLRequest(url: url)
request.timeoutInterval = 45
request.setValue("LektorenPlan/0.1 (macOS; Pfarrei Bad Godesberg)", forHTTPHeaderField: "User-Agent")
request.setValue("LektorenPlan/0.9 (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)
+28
View File
@@ -35,6 +35,15 @@ public enum Role: String, Codable, CaseIterable, Identifiable, Sendable, Hashabl
case .helper: "hand.raised.fill"
}
}
/// The other role a service may need. Lector and communion helper do not
/// exclude each other, so one person can fill both at the same service.
public var complementary: Role {
switch self {
case .lector: .helper
case .helper: .lector
}
}
}
// MARK: - Church
@@ -155,6 +164,12 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
return "\(firstName) \(initial)."
}
/// Compact display for the calendar: surname in full, first name abbreviated.
public var abbreviatedName: String {
guard let initial = firstName.first else { return lastName }
return "\(initial). \(lastName)"
}
public var roleLabel: String {
let ordered = Role.allCases.filter { roles.contains($0) }
return ordered.map(\.title).joined(separator: " · ")
@@ -292,6 +307,9 @@ public enum ServiceKind: String, Codable, CaseIterable, Sendable {
public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
public var id: String
public var churchID: String
/// Free-text location for special services (e.g. open-air worship).
/// `nil` means the service takes place in the assigned church.
public var location: String?
public var templateID: String?
public var date: Date
public var timeMinutes: Int
@@ -306,6 +324,7 @@ public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
public init(
id: String = UUID().uuidString,
churchID: String,
location: String? = nil,
templateID: String? = nil,
date: Date,
timeMinutes: Int,
@@ -319,6 +338,8 @@ public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
) {
self.id = id
self.churchID = churchID
let trimmedLocation = location?.trimmingCharacters(in: .whitespacesAndNewlines)
self.location = (trimmedLocation?.isEmpty ?? true) ? nil : trimmedLocation
self.templateID = templateID
self.date = DayMath.normalize(date)
self.timeMinutes = timeMinutes
@@ -331,6 +352,10 @@ public struct ServiceOccurrence: Identifiable, Codable, Hashable, Sendable {
self.createdAt = createdAt
}
public func placeName(church: Church) -> String {
location ?? church.name
}
public var timeLabel: String { DayMath.timeString(minutes: timeMinutes) }
public var dateKey: String { DayMath.key(date) }
public var requiredSlots: Int { lectorsNeeded + helpersNeeded }
@@ -877,6 +902,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
public var weightChurchPreference: Double
public var weightServicePreference: Double
public var weightFairness: Double
public var weightDualRolePreference: Double
public var maxAssignmentsPerDay: Int
public init(
@@ -886,6 +912,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
weightChurchPreference: Double = 8,
weightServicePreference: Double = 4,
weightFairness: Double = 2.2,
weightDualRolePreference: Double = 14,
maxAssignmentsPerDay: Int = 1
) {
self.replaceExisting = replaceExisting
@@ -894,6 +921,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
self.weightChurchPreference = weightChurchPreference
self.weightServicePreference = weightServicePreference
self.weightFairness = weightFairness
self.weightDualRolePreference = weightDualRolePreference
self.maxAssignmentsPerDay = maxAssignmentsPerDay
}
}
+51 -14
View File
@@ -39,7 +39,9 @@ public struct ServicePlanner {
var totalByPerson: [String: Int] = [:]
var monthByPerson: [String: Int] = [:]
var dayByPerson: [String: Int] = [:]
// Count distinct services per day. Both roles at the same service do not
// count as a double booking, so one person can be lector and helper there.
var dayServicesByPerson: [String: Set<String>] = [:]
var churchByPerson: [String: [String: Int]] = [:]
var lastDateByPerson: [String: Date] = [:]
@@ -48,7 +50,7 @@ public struct ServicePlanner {
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
dayServicesByPerson["\(assignment.personID)|\(service.dateKey)", default: []].insert(service.id)
churchByPerson[assignment.personID, default: [:]][service.churchID, default: 0] += 1
let previous = lastDateByPerson[assignment.personID]
if previous == nil || service.date > previous! {
@@ -66,6 +68,13 @@ public struct ServicePlanner {
var newAssignments: [Assignment] = []
for service in sortedServices {
// Roles already covered at this service. A person may appear in both
// roles, but not twice in the same role.
var assignedRolesByPerson: [String: Set<Role>] = [:]
for assignment in working where assignment.serviceID == service.id {
assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role)
}
for role in Role.allCases {
let required = service.requiredCount(for: role)
guard required > 0 else { continue }
@@ -73,7 +82,6 @@ public struct ServicePlanner {
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,
@@ -82,10 +90,10 @@ public struct ServicePlanner {
absencesByPerson: absencesByPerson,
totalByPerson: totalByPerson,
monthByPerson: monthByPerson,
dayByPerson: dayByPerson,
dayServicesByPerson: dayServicesByPerson,
churchByPerson: churchByPerson,
lastDateByPerson: lastDateByPerson,
alreadyAssigned: alreadyAssigned
assignedRolesByPerson: assignedRolesByPerson
)
switch result {
case .success(let person):
@@ -98,9 +106,10 @@ public struct ServicePlanner {
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
dayServicesByPerson["\(person.id)|\(service.dateKey)", default: []].insert(service.id)
churchByPerson[person.id, default: [:]][service.churchID, default: 0] += 1
lastDateByPerson[person.id] = service.date
assignedRolesByPerson[person.id, default: []].insert(role)
case .failure(let reason):
unfilled.append(UnfilledSlot(
service: service,
@@ -144,17 +153,18 @@ public struct ServicePlanner {
absencesByPerson: [String: [Absence]],
totalByPerson: [String: Int],
monthByPerson: [String: Int],
dayByPerson: [String: Int],
dayServicesByPerson: [String: Set<String>],
churchByPerson: [String: [String: Int]],
lastDateByPerson: [String: Date],
alreadyAssigned: Set<String>
assignedRolesByPerson: [String: Set<Role>]
) -> CandidateResult {
var candidates: [(Person, Double)] = []
var blockedReasons: [String: Int] = [:]
var eligiblePeople: [Person] = []
for person in people where person.canFill(role) {
guard !alreadyAssigned.contains(person.id) else {
blockedReasons["bereits im Gottesdienst", default: 0] += 1
let assignedRoles = assignedRolesByPerson[person.id] ?? []
guard !assignedRoles.contains(role) else {
blockedReasons["bereits für diesen Dienst eingeteilt", default: 0] += 1
continue
}
if let absences = absencesByPerson[person.id], absences.contains(where: { $0.overlaps(service.date) }) {
@@ -173,13 +183,41 @@ public struct ServicePlanner {
blockedReasons["Monatslimit erreicht", default: 0] += 1
continue
}
let usedThisDay = dayByPerson["\(person.id)|\(service.dateKey)", default: 0]
if usedThisDay >= options.maxAssignmentsPerDay {
let usedServicesThisDay = dayServicesByPerson["\(person.id)|\(service.dateKey)", default: []]
// A second role at the very same service is not a double booking.
if usedServicesThisDay.count >= options.maxAssignmentsPerDay,
!usedServicesThisDay.isSubset(of: [service.id]) {
blockedReasons["bereits an diesem Tag", default: 0] += 1
continue
}
eligiblePeople.append(person)
}
// The dual-role preference is a tie-breaker, not a way to concentrate
// assignments on one person. If another suitable person has noticeably
// fewer assignments, fairness takes priority over giving both roles to
// the same person.
let minimumTotal = eligiblePeople.map { totalByPerson[$0.id, default: 0] }.min() ?? 0
let fairnessSlack = 1
var candidates: [(Person, Double)] = []
for person in eligiblePeople {
let assignedRoles = assignedRolesByPerson[person.id] ?? []
let total = totalByPerson[person.id, default: 0]
let withinFairnessReach = total - minimumTotal <= fairnessSlack
var score = 10.0
if withinFairnessReach, assignedRoles.contains(role.complementary) {
// The same person already covers the other role here — prefer
// keeping both duties with them while the distribution stays fair.
score += options.weightDualRolePreference
} else if withinFairnessReach,
service.rolesNeeded.count > 1,
person.roles.contains(where: { $0 != role && service.requiredCount(for: $0) > 0 }) {
// On services needing both roles, favour people who can cover both.
score += options.weightDualRolePreference
}
if person.preferredChurchIDs.contains(service.churchID) {
score += options.weightChurchPreference
}
@@ -197,7 +235,6 @@ public struct ServicePlanner {
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