Versendung mit .ics Kalenderdatei

This commit is contained in:
concierge committed 2026-11-18 08:13:10 +01:00
1 parent c08d43e7dd
commit dc20d7ec5a
13 files changed
+650 -54

No files matched your search

@@ -8,6 +8,7 @@ struct DispatchAssignment: Identifiable, Hashable {
var date: Date
var timeMinutes: Int
var church: String
var place: String
var title: String
var role: Role
+71 -8
View File
@@ -174,6 +174,17 @@ final class PlanModel: ObservableObject {
Ihr Pfarreiteam
"""
/// The editable dispatch wording is stored per local user so several people
/// sharing one installation keep their own style. The unsuffixed keys are
/// the legacy shared value and remain the fallback.
static var dispatchUserIntroKey: String { "dispatch.intro.user.\(dispatchLocalUserKey)" }
static var dispatchUserGreetingKey: String { "dispatch.greeting.user.\(dispatchLocalUserKey)" }
private static var dispatchLocalUserKey: String {
let name = NSUserName().trimmingCharacters(in: .whitespacesAndNewlines)
return name.isEmpty ? "local" : name
}
let db: AppDatabase
@Published var section: AppSection = .planning
@@ -1062,6 +1073,7 @@ final class PlanModel: ObservableObject {
date: row.date,
timeMinutes: service.service.timeMinutes,
church: service.church.shortName,
place: service.service.placeName(church: service.church),
title: service.service.title,
role: assignment.role
))
@@ -1074,6 +1086,27 @@ final class PlanModel: ObservableObject {
}
}
/// Builds calendar events for one recipient. Service times are wall-clock
/// times in the parish, so they stay floating local times in the `.ics`.
func dispatchCalendarEvents(_ assignments: [DispatchAssignment]) -> [CalendarEvent] {
assignments.map { assignment in
let start = DayMath.calendar.date(
bySettingHour: assignment.timeMinutes / 60,
minute: assignment.timeMinutes % 60,
second: 0,
of: assignment.date
) ?? assignment.date
return CalendarEvent(
uid: assignment.id,
start: start,
durationMinutes: 60,
summary: assignment.title,
location: assignment.place,
description: "Dienst: \(assignment.role.title)"
)
}
}
func loadDispatch() {
do {
dispatchPreferences = try db.dispatchPreferences()
@@ -1082,18 +1115,22 @@ final class PlanModel: ObservableObject {
alertTitle = "Versendung konnte nicht geladen werden"
alertMessage = error.localizedDescription
}
if let stored = db.setting("dispatch.intro"), !stored.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
if let stored = db.setting(Self.dispatchUserIntroKey), !stored.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
dispatchIntro = stored
} else if let stored = db.setting("dispatch.intro"), !stored.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
dispatchIntro = stored
} else {
dispatchIntro = Self.defaultDispatchIntro
}
dispatchGreeting = db.setting("dispatch.greeting") ?? Self.defaultDispatchGreeting
dispatchGreeting = db.setting(Self.dispatchUserGreetingKey)
?? db.setting("dispatch.greeting")
?? Self.defaultDispatchGreeting
}
/// Persists the texts and every currently visible preference.
func saveDispatchSettings(showConfirmation: Bool = true) {
db.setSetting("dispatch.intro", value: dispatchIntro)
db.setSetting("dispatch.greeting", value: dispatchGreeting)
db.setSetting(Self.dispatchUserIntroKey, value: dispatchIntro)
db.setSetting(Self.dispatchUserGreetingKey, value: dispatchGreeting)
for recipient in dispatchRecipients {
db.saveDispatchPreference(recipient.preference, personID: recipient.id)
}
@@ -1117,6 +1154,7 @@ final class PlanModel: ObservableObject {
func dispatchEmailBody(for recipient: DispatchRecipient) -> String {
var parts: [String] = [resolvedDispatchText(dispatchIntro)]
parts.append("Ihre Einsätze im Zeitraum:\n\n" + dispatchAssignmentLines(recipient.assignments))
parts.append(Self.dispatchAttachmentHint)
let greeting = resolvedDispatchText(dispatchGreeting)
if !greeting.isEmpty {
parts.append(greeting)
@@ -1124,6 +1162,9 @@ final class PlanModel: ObservableObject {
return parts.joined(separator: "\n\n")
}
static let dispatchAttachmentHint = "Im Anhang finden Sie den Plan als PDF sowie eine Kalenderdatei (.ics), "
+ "die Sie in Ihren Kalender importieren können."
func dispatchAssignmentLines(_ assignments: [DispatchAssignment]) -> String {
guard !assignments.isEmpty else {
return "Für Sie sind in diesem Zeitraum keine Einsätze eingetragen."
@@ -1189,18 +1230,30 @@ final class PlanModel: ObservableObject {
continue
}
let calendarURL = directory.appendingPathComponent(dispatchCalendarFilename(for: recipient))
let calendar = CalendarExport.ics(
calendarName: "Gottesdienstplan \(range.shortTitle)",
events: dispatchCalendarEvents(recipient.assignments)
)
do {
try Data(calendar.utf8).write(to: calendarURL, options: .atomic)
} catch {
failure("Kalenderdatei konnte nicht gespeichert werden: \(error.localizedDescription)")
continue
}
service.recipients = [email]
service.subject = dispatchSubject()
let body = dispatchEmailBody(for: recipient)
DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.4) {
service.perform(withItems: [body, fileURL])
service.perform(withItems: [body, fileURL, calendarURL])
}
opened += 1
entries.append(DispatchLogEntry(
batchID: batchID, rangeStart: range.start, rangeEnd: range.end,
personID: recipient.id, personName: recipient.person.fullName,
channel: .email, variant: variant, email: email,
status: .mail, detail: "Anhang: \(variant.shortTitle)", createdAt: createdAt
status: .mail, detail: "Anhänge: \(variant.shortTitle), Kalender (.ics)", createdAt: createdAt
))
}
@@ -1311,12 +1364,22 @@ final class PlanModel: ObservableObject {
}
private func dispatchFilename(for recipient: DispatchRecipient, variant: PlanListVariant) -> String {
let base = recipient.person.fullName
"LektorenPlan-\(dispatchPersonFileComponent(recipient))-\(variant.rawValue)-\(DayMath.key(range.start)).pdf"
}
/// The calendar file is generated per person, so its name carries the same
/// person component as the PDF to avoid overwriting files in the shared
/// temporary dispatch directory.
private func dispatchCalendarFilename(for recipient: DispatchRecipient) -> String {
"LektorenPlan-\(dispatchPersonFileComponent(recipient))-Kalender-\(DayMath.key(range.start)).ics"
}
private func dispatchPersonFileComponent(_ recipient: DispatchRecipient) -> String {
recipient.person.fullName
.folding(options: .diacriticInsensitive, locale: .current)
.replacingOccurrences(of: " ", with: "-")
.components(separatedBy: CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_")).inverted)
.joined()
return "LektorenPlan-\(base)-\(variant.rawValue)-\(DayMath.key(range.start)).pdf"
}
private func dispatchTempDirectory() -> URL {
@@ -2,8 +2,8 @@ import SwiftUI
import LektorenPlanCore
/// Dispatch view: decides who receives the plan of the current period, by
/// e-mail (opened in the default mail client with a personal PDF attachment)
/// or as one combined printable packet.
/// e-mail (opened in the default mail client with a personal PDF and calendar
/// attachment) or as one combined printable packet.
struct DispatchView: View {
@EnvironmentObject private var model: PlanModel
@@ -132,7 +132,7 @@ struct DispatchView: View {
cardHeader(
icon: "text.alignleft",
title: "Anschreiben",
subtitle: "Gilt einheitlich für alle E-Mails und Vorblätter",
subtitle: "Ihr Text – gespeichert für dieses Benutzerkonto",
tint: LP.accent
)
@@ -183,7 +183,7 @@ struct DispatchView: View {
Image(systemName: "curlybraces")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
Text("Platzhalter {start} und {end} werden beim Versand durch „\(DayMath.mediumString(model.range.start))“ und „\(DayMath.mediumString(model.range.end))“ ersetzt. Zwischen Einleitung und Gruß steht die persönliche Einsatzübersicht.")
Text("Platzhalter {start} und {end} werden beim Versand durch „\(DayMath.mediumString(model.range.start))“ und „\(DayMath.mediumString(model.range.end))“ ersetzt. Zwischen Einleitung und Gruß stehen die persönliche Einsatzübersicht und ein Hinweis auf die beiden Anhänge (PDF und Kalenderdatei).")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
@@ -212,7 +212,7 @@ struct DispatchView: View {
Image(systemName: "info.circle")
.font(.system(size: 10, weight: .semibold))
.foregroundStyle(LP.accent)
Text("Ohne hinterlegte E-Mail-Adresse wird automatisch gedruckt. E-Mails werden als Entwurf im Standard-Mailprogramm geöffnet – mit persönlichem Text und dem gewählten PDF.")
Text("Ohne hinterlegte E-Mail-Adresse wird automatisch gedruckt. E-Mails werden als Entwurf im Standard-Mailprogramm geöffnet – mit persönlichem Text, dem gewählten PDF und einer Kalenderdatei (.ics) mit den eigenen Einsätzen.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
@@ -0,0 +1,134 @@
import Foundation
/// One appointment for the iCalendar export. The start is written as a
/// floating local time so calendar applications show the parish's wall-clock
/// time regardless of the device time zone.
public struct CalendarEvent: Hashable, Sendable {
public var uid: String
public var start: Date
public var durationMinutes: Int
public var summary: String
public var location: String
public var description: String
public init(
uid: String,
start: Date,
durationMinutes: Int = 60,
summary: String,
location: String = "",
description: String = ""
) {
self.uid = uid
self.start = start
self.durationMinutes = durationMinutes
self.summary = summary
self.location = location
self.description = description
}
}
/// Builds a published iCalendar document with one timed VEVENT per assignment.
public enum CalendarExport {
/// Returns a complete `.ics` document in RFC 5545 format.
public static func ics(
calendarName: String,
events: [CalendarEvent],
generatedAt: Date = Date()
) -> String {
let sorted = events.sorted { $0.start < $1.start }
var output = ""
appendLine("BEGIN:VCALENDAR", to: &output)
appendLine("VERSION:2.0", to: &output)
appendLine("PRODID:-//LektorenPlan//Gottesdienstplan//DE", to: &output)
appendLine("CALSCALE:GREGORIAN", to: &output)
appendLine("METHOD:PUBLISH", to: &output)
appendLine("X-WR-CALNAME:\(escape(calendarName))", to: &output)
let stamp = utcFormatter.string(from: generatedAt)
for event in sorted {
let duration = event.durationMinutes > 0 ? event.durationMinutes : 60
let end = event.start.addingTimeInterval(TimeInterval(duration * 60))
appendLine("BEGIN:VEVENT", to: &output)
appendLine("UID:\(escape(event.uid))@lektorenplan", to: &output)
appendLine("DTSTAMP:\(stamp)", to: &output)
appendLine("DTSTART:\(localFormatter.string(from: event.start))", to: &output)
appendLine("DTEND:\(localFormatter.string(from: end))", to: &output)
appendLine("SUMMARY:\(escape(event.summary))", to: &output)
let location = event.location.trimmingCharacters(in: .whitespacesAndNewlines)
if !location.isEmpty {
appendLine("LOCATION:\(escape(location))", to: &output)
}
let description = event.description.trimmingCharacters(in: .whitespacesAndNewlines)
if !description.isEmpty {
appendLine("DESCRIPTION:\(escape(description))", to: &output)
}
appendLine("END:VEVENT", to: &output)
}
appendLine("END:VCALENDAR", to: &output)
return output
}
/// A filesystem-safe attachment name, for example
/// `LektorenPlan-bad-godesberg-Kalender-2026-03-01.ics`.
public static func filename(prefix: String, start: Date) -> String {
var base = "LektorenPlan"
let trimmed = prefix.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty {
base += "-" + sanitizedComponent(trimmed)
}
return "\(base)-Kalender-\(DayMath.key(start)).ics"
}
private static func sanitizedComponent(_ value: String) -> String {
let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))
let folded = value.folding(options: .diacriticInsensitive, locale: .current)
return folded
.replacingOccurrences(of: " ", with: "-")
.components(separatedBy: allowed.inverted)
.joined()
}
private static let localFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = DayMath.calendar.timeZone
formatter.dateFormat = "yyyyMMdd'T'HHmmss"
return formatter
}()
private static let utcFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'"
return formatter
}()
/// Appends one content line and folds it at 75 octets as required by RFC 5545.
private static func appendLine(_ line: String, to output: inout String) {
let limit = 75
var used = 0
for character in line {
let width = String(character).utf8.count
if used + width > limit {
output += "\r\n "
used = 1
}
output.append(character)
used += width
}
output += "\r\n"
}
/// Applies the TEXT escaping rules of RFC 5545.
private static func escape(_ value: String) -> String {
var escaped = value.replacingOccurrences(of: "\\", with: "\\\\")
escaped = escaped.replacingOccurrences(of: ";", with: "\\;")
escaped = escaped.replacingOccurrences(of: ",", with: "\\,")
escaped = escaped.replacingOccurrences(of: "\r\n", with: "\\n")
escaped = escaped.replacingOccurrences(of: "\n", with: "\\n")
escaped = escaped.replacingOccurrences(of: "\r", with: "\\n")
return escaped
}
}