Versendung mit .ics Kalenderdatei
This commit is contained in:
1 parent
c08d43e7dd
commit
dc20d7ec5a
13 files changed
+649
-53
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
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -425,6 +425,75 @@ final class CoreTests: XCTestCase {
|
||||
XCTAssertEqual(stats.preferenceRate, 0)
|
||||
}
|
||||
|
||||
func testCalendarExportWritesTimedEvents() {
|
||||
let start = DayMath.calendar.date(from: DateComponents(
|
||||
year: 2026, month: 11, day: 22, hour: 18, minute: 0
|
||||
))!
|
||||
let ics = CalendarExport.ics(
|
||||
calendarName: "Gottesdienstplan Pfarrei",
|
||||
events: [
|
||||
CalendarEvent(
|
||||
uid: "assignment-1",
|
||||
start: start,
|
||||
durationMinutes: 60,
|
||||
summary: "Abendmesse, Hochfest",
|
||||
location: "St. Andreas",
|
||||
description: "Dienst: Lektor; Bitte 10 Minuten früher da sein."
|
||||
)
|
||||
],
|
||||
generatedAt: start
|
||||
)
|
||||
for want in [
|
||||
"BEGIN:VCALENDAR\r\n",
|
||||
"VERSION:2.0\r\n",
|
||||
"BEGIN:VEVENT\r\n",
|
||||
"UID:assignment-1@lektorenplan\r\n",
|
||||
"DTSTART:20261122T180000\r\n",
|
||||
"DTEND:20261122T190000\r\n",
|
||||
"SUMMARY:Abendmesse\\, Hochfest\r\n",
|
||||
"LOCATION:St. Andreas\r\n",
|
||||
"DESCRIPTION:Dienst: Lektor\\; Bitte 10 Minuten früher da sein.\r\n",
|
||||
"END:VCALENDAR\r\n",
|
||||
] {
|
||||
XCTAssertTrue(ics.contains(want), "calendar misses \(want):\n\(ics)")
|
||||
}
|
||||
XCTAssertFalse(ics.contains("\n\n"), "calendar must use CRLF line endings")
|
||||
}
|
||||
|
||||
func testCalendarExportFoldsLongLines() {
|
||||
let start = DayMath.calendar.date(from: DateComponents(
|
||||
year: 2026, month: 11, day: 22, hour: 10, minute: 0
|
||||
))!
|
||||
let long = String(repeating: "ä", count: 90)
|
||||
let ics = CalendarExport.ics(
|
||||
calendarName: "Plan",
|
||||
events: [CalendarEvent(uid: "x", start: start, summary: long)]
|
||||
)
|
||||
for line in ics.components(separatedBy: "\r\n") {
|
||||
XCTAssertLessThanOrEqual(line.utf8.count, 75, "line exceeds 75 octets: \(line)")
|
||||
}
|
||||
XCTAssertTrue(ics.contains("\r\n "), "expected folded continuation line")
|
||||
}
|
||||
|
||||
func testCalendarExportEscapesBackslashesAndNewlines() {
|
||||
let ics = CalendarExport.ics(
|
||||
calendarName: "Plan",
|
||||
events: [CalendarEvent(
|
||||
uid: "x", start: Date(), summary: "A\\B", description: "Zeile 1\nZeile 2"
|
||||
)]
|
||||
)
|
||||
XCTAssertTrue(ics.contains("SUMMARY:A\\\\B\r\n"), ics)
|
||||
XCTAssertTrue(ics.contains("DESCRIPTION:Zeile 1\\nZeile 2\r\n"), ics)
|
||||
}
|
||||
|
||||
func testCalendarFilenameIsFilesystemSafe() {
|
||||
let start = DayMath.date(fromKey: "2026-03-01")!
|
||||
XCTAssertEqual(
|
||||
CalendarExport.filename(prefix: "bad-godesberg", start: start),
|
||||
"LektorenPlan-bad-godesberg-Kalender-2026-03-01.ics"
|
||||
)
|
||||
}
|
||||
|
||||
func testAPIParsing() throws {
|
||||
let json = """
|
||||
{"Kalendername":"Test","Zelebrationen":{
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CalendarEvent is one appointment for an iCalendar export. Start is written as
|
||||
// a floating local time so calendar applications show the church's local time
|
||||
// regardless of the device time zone.
|
||||
type CalendarEvent struct {
|
||||
UID string
|
||||
Start time.Time
|
||||
DurationMinutes int
|
||||
Summary string
|
||||
Location string
|
||||
Description string
|
||||
}
|
||||
|
||||
// CalendarICS builds a published iCalendar document with one VEVENT per
|
||||
// assignment. Timed events make the personal assignments useful in the common
|
||||
// calendar applications.
|
||||
func CalendarICS(calendarName string, events []CalendarEvent) string {
|
||||
sorted := append([]CalendarEvent(nil), events...)
|
||||
sort.SliceStable(sorted, func(i, j int) bool {
|
||||
return sorted[i].Start.Before(sorted[j].Start)
|
||||
})
|
||||
|
||||
var builder strings.Builder
|
||||
writeICSLine(&builder, "BEGIN:VCALENDAR")
|
||||
writeICSLine(&builder, "VERSION:2.0")
|
||||
writeICSLine(&builder, "PRODID:-//LektorenPlan//Gottesdienstplan//DE")
|
||||
writeICSLine(&builder, "CALSCALE:GREGORIAN")
|
||||
writeICSLine(&builder, "METHOD:PUBLISH")
|
||||
writeICSLine(&builder, "X-WR-CALNAME:"+escapeICSText(calendarName))
|
||||
stamp := time.Now().UTC().Format("20060102T150405Z")
|
||||
for _, event := range sorted {
|
||||
duration := event.DurationMinutes
|
||||
if duration <= 0 {
|
||||
duration = 60
|
||||
}
|
||||
writeICSLine(&builder, "BEGIN:VEVENT")
|
||||
writeICSLine(&builder, "UID:"+escapeICSText(event.UID)+"@lektorenplan")
|
||||
writeICSLine(&builder, "DTSTAMP:"+stamp)
|
||||
writeICSLine(&builder, "DTSTART:"+event.Start.Format("20060102T150405"))
|
||||
writeICSLine(&builder, "DTEND:"+event.Start.Add(time.Duration(duration)*time.Minute).Format("20060102T150405"))
|
||||
writeICSLine(&builder, "SUMMARY:"+escapeICSText(event.Summary))
|
||||
if strings.TrimSpace(event.Location) != "" {
|
||||
writeICSLine(&builder, "LOCATION:"+escapeICSText(event.Location))
|
||||
}
|
||||
if strings.TrimSpace(event.Description) != "" {
|
||||
writeICSLine(&builder, "DESCRIPTION:"+escapeICSText(event.Description))
|
||||
}
|
||||
writeICSLine(&builder, "END:VEVENT")
|
||||
}
|
||||
writeICSLine(&builder, "END:VCALENDAR")
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// writeICSLine folds content lines at 75 octets as required by RFC 5545.
|
||||
func writeICSLine(builder *strings.Builder, line string) {
|
||||
const limit = 75
|
||||
bytesUsed := 0
|
||||
for index, r := range line {
|
||||
width := len(string(r))
|
||||
if bytesUsed+width > limit {
|
||||
builder.WriteString("\r\n ")
|
||||
bytesUsed = 1
|
||||
}
|
||||
if index == 0 {
|
||||
builder.WriteRune(r)
|
||||
bytesUsed += width
|
||||
continue
|
||||
}
|
||||
builder.WriteRune(r)
|
||||
bytesUsed += width
|
||||
}
|
||||
builder.WriteString("\r\n")
|
||||
}
|
||||
|
||||
// escapeICSText applies the escaping rules for TEXT values in RFC 5545.
|
||||
func escapeICSText(value string) string {
|
||||
value = strings.ReplaceAll(value, "\\", "\\\\")
|
||||
value = strings.ReplaceAll(value, ";", "\\;")
|
||||
value = strings.ReplaceAll(value, ",", "\\,")
|
||||
value = strings.ReplaceAll(value, "\r\n", "\\n")
|
||||
value = strings.ReplaceAll(value, "\n", "\\n")
|
||||
value = strings.ReplaceAll(value, "\r", "\\n")
|
||||
return value
|
||||
}
|
||||
|
||||
// CalendarFilename is a filesystem-safe attachment name.
|
||||
func CalendarFilename(prefix, start string) string {
|
||||
name := "LektorenPlan"
|
||||
if trimmed := strings.TrimSpace(prefix); trimmed != "" {
|
||||
name += "-" + trimmed
|
||||
}
|
||||
return fmt.Sprintf("%s-Kalender-%s.ics", name, start)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCalendarICSWritesTimedEvents(t *testing.T) {
|
||||
start := time.Date(2026, 11, 22, 18, 0, 0, 0, time.Local)
|
||||
ics := CalendarICS("Gottesdienstplan Pfarrei", []CalendarEvent{
|
||||
{
|
||||
UID: "assignment-1", Start: start, DurationMinutes: 60,
|
||||
Summary: "Abendmesse, Hochfest", Location: "St. Andreas",
|
||||
Description: "Dienst: Lektor; Bitte 10 Minuten früher da sein.",
|
||||
},
|
||||
})
|
||||
for _, want := range []string{
|
||||
"BEGIN:VCALENDAR\r\n",
|
||||
"VERSION:2.0\r\n",
|
||||
"BEGIN:VEVENT\r\n",
|
||||
"UID:assignment-1@lektorenplan\r\n",
|
||||
"DTSTART:20261122T180000\r\n",
|
||||
"DTEND:20261122T190000\r\n",
|
||||
"SUMMARY:Abendmesse\\, Hochfest\r\n",
|
||||
"LOCATION:St. Andreas\r\n",
|
||||
"DESCRIPTION:Dienst: Lektor\\; Bitte 10 Minuten früher da sein.\r\n",
|
||||
"END:VCALENDAR\r\n",
|
||||
} {
|
||||
if !strings.Contains(ics, want) {
|
||||
t.Fatalf("calendar misses %q:\n%s", want, ics)
|
||||
}
|
||||
}
|
||||
if strings.Contains(ics, "\n\n") {
|
||||
t.Fatal("calendar must use CRLF line endings")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalendarICSFoldsLongLines(t *testing.T) {
|
||||
start := time.Date(2026, 11, 22, 10, 0, 0, 0, time.Local)
|
||||
long := strings.Repeat("ä", 90)
|
||||
ics := CalendarICS("Plan", []CalendarEvent{{UID: "x", Start: start, Summary: long}})
|
||||
for _, line := range strings.Split(ics, "\r\n") {
|
||||
if len([]byte(line)) > 75 {
|
||||
t.Fatalf("line exceeds 75 octets: %q", line)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(ics, "\r\n ") {
|
||||
t.Fatal("expected folded continuation line")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalendarICSEscapesBackslashesAndNewlines(t *testing.T) {
|
||||
ics := CalendarICS("Plan", []CalendarEvent{{
|
||||
UID: "x", Start: time.Now(), Summary: "A\\B", Description: "Zeile 1\nZeile 2",
|
||||
}})
|
||||
if !strings.Contains(ics, "SUMMARY:A\\\\B\r\n") {
|
||||
t.Fatalf("backslash not escaped:\n%s", ics)
|
||||
}
|
||||
if !strings.Contains(ics, "DESCRIPTION:Zeile 1\\nZeile 2\r\n") {
|
||||
t.Fatalf("newline not escaped:\n%s", ics)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
func TestDispatchCalendarEventsMapAssignments(t *testing.T) {
|
||||
day := time.Date(2026, 3, 8, 0, 0, 0, 0, time.Local)
|
||||
events := dispatchCalendarEvents([]dispatchAssignmentView{
|
||||
{
|
||||
ID: "a-1", Date: day, SortMinutes: 18 * 60, Title: "Abendmesse",
|
||||
Place: "St. Andreas", RoleLabel: "Lektor",
|
||||
},
|
||||
})
|
||||
if len(events) != 1 {
|
||||
t.Fatalf("events = %d, want 1", len(events))
|
||||
}
|
||||
event := events[0]
|
||||
if event.Start.Hour() != 18 || event.Start.Minute() != 0 || event.Start.Day() != 8 {
|
||||
t.Fatalf("start = %v", event.Start)
|
||||
}
|
||||
if event.UID != "a-1" {
|
||||
t.Fatalf("UID = %q", event.UID)
|
||||
}
|
||||
if event.DurationMinutes != 60 {
|
||||
t.Fatalf("duration = %d, want 60", event.DurationMinutes)
|
||||
}
|
||||
if event.Summary != "Abendmesse" || event.Location != "St. Andreas" {
|
||||
t.Fatalf("unexpected event: %+v", event)
|
||||
}
|
||||
if event.Description != "Dienst: Lektor" {
|
||||
t.Fatalf("description = %q", event.Description)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchEmailBodyMentionsBothAttachments(t *testing.T) {
|
||||
rng := domain.DayRange{
|
||||
Start: time.Date(2026, 3, 1, 0, 0, 0, 0, time.Local),
|
||||
End: time.Date(2026, 3, 31, 0, 0, 0, 0, time.Local),
|
||||
}
|
||||
assignments := []dispatchAssignmentView{{
|
||||
Date: rng.Start, DateLabel: "1. März 2026", TimeLabel: "18:00",
|
||||
Church: "St. Andreas", Title: "Abendmesse", RoleLabel: "Lektor", SortMinutes: 18 * 60,
|
||||
}}
|
||||
|
||||
sent := dispatchEmailBody("Einleitung", "Gruß", rng, assignments, true)
|
||||
for _, want := range []string{"Einleitung", "Abendmesse", "PDF", "Kalenderdatei (.ics)", "Gruß"} {
|
||||
if !strings.Contains(sent, want) {
|
||||
t.Fatalf("sent body misses %q:\n%s", want, sent)
|
||||
}
|
||||
}
|
||||
if strings.Index(sent, "Kalenderdatei") > strings.Index(sent, "Gruß") {
|
||||
t.Fatal("attachment hint must appear before the greeting")
|
||||
}
|
||||
|
||||
draft := dispatchEmailBody("Einleitung", "Gruß", rng, assignments, false)
|
||||
if strings.Contains(draft, "Kalenderdatei") {
|
||||
t.Fatalf("draft body must not mention attachments:\n%s", draft)
|
||||
}
|
||||
}
|
||||
@@ -32,13 +32,25 @@ const (
|
||||
|
||||
dispatchIntroKey = "dispatch.intro"
|
||||
dispatchGreetingKey = "dispatch.greeting"
|
||||
// The editable wording is stored per editor account so two editors can keep
|
||||
// their own style. The unsuffixed keys are the legacy tenant-wide value and
|
||||
// remain the fallback for accounts that have not saved their own text yet.
|
||||
dispatchUserIntroKey = "dispatch.intro.user."
|
||||
dispatchUserGreetingKey = "dispatch.greeting.user."
|
||||
)
|
||||
|
||||
// dispatchUserKey scopes a dispatch text setting to one editor account.
|
||||
func dispatchUserKey(prefix, userID string) string {
|
||||
return prefix + userID
|
||||
}
|
||||
|
||||
type dispatchAssignmentView struct {
|
||||
ID string
|
||||
Date time.Time
|
||||
DateLabel string
|
||||
TimeLabel string
|
||||
Church string
|
||||
Place string
|
||||
Title string
|
||||
Role domain.Role
|
||||
RoleLabel string
|
||||
@@ -147,20 +159,27 @@ func resolveDispatchText(value string, rng domain.DayRange) string {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
|
||||
// dispatchTexts returns the stored intro and greeting. An empty stored intro
|
||||
// falls back to the default wording, while an empty greeting stays empty so
|
||||
// editors can deliberately omit it.
|
||||
func (s *Server) dispatchTexts(ctx context.Context, tenantID string) (intro, greeting string) {
|
||||
// dispatchTexts returns the stored intro and greeting for one editor account.
|
||||
// An empty stored intro falls back to the default wording, while an empty
|
||||
// greeting stays empty so editors can deliberately omit it. Accounts without
|
||||
// their own text inherit the legacy tenant-wide wording.
|
||||
func (s *Server) dispatchTexts(ctx context.Context, tenantID, userID string) (intro, greeting string) {
|
||||
settings, err := s.store.AllTenantSettings(ctx, tenantID)
|
||||
if err != nil {
|
||||
return defaultDispatchIntro, defaultDispatchGreeting
|
||||
}
|
||||
intro = defaultDispatchIntro
|
||||
if value, ok := settings[dispatchIntroKey]; ok && strings.TrimSpace(value) != "" {
|
||||
if value, ok := settings[dispatchUserKey(dispatchUserIntroKey, userID)]; ok {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
intro = value
|
||||
}
|
||||
} else if value, ok := settings[dispatchIntroKey]; ok && strings.TrimSpace(value) != "" {
|
||||
intro = value
|
||||
}
|
||||
greeting = defaultDispatchGreeting
|
||||
if value, ok := settings[dispatchGreetingKey]; ok {
|
||||
if value, ok := settings[dispatchUserKey(dispatchUserGreetingKey, userID)]; ok {
|
||||
greeting = value
|
||||
} else if value, ok := settings[dispatchGreetingKey]; ok {
|
||||
greeting = value
|
||||
}
|
||||
return intro, greeting
|
||||
@@ -204,9 +223,11 @@ func dispatchAssignments(rows []domain.DayPlanRow, personID string) []dispatchAs
|
||||
continue
|
||||
}
|
||||
out = append(out, dispatchAssignmentView{
|
||||
Date: row.Date, DateLabel: domain.MediumString(row.Date),
|
||||
ID: assignment.ID, Date: row.Date, DateLabel: domain.MediumString(row.Date),
|
||||
TimeLabel: domain.TimeString(service.Service.TimeMinutes),
|
||||
Church: service.Church.ShortName, Title: service.Service.Title,
|
||||
Church: service.Church.ShortName,
|
||||
Place: service.Service.PlaceName(service.Church),
|
||||
Title: service.Service.Title,
|
||||
Role: assignment.Role, RoleLabel: assignment.Role.Title(),
|
||||
SortMinutes: service.Service.TimeMinutes,
|
||||
})
|
||||
@@ -222,6 +243,25 @@ func dispatchAssignments(rows []domain.DayPlanRow, personID string) []dispatchAs
|
||||
return out
|
||||
}
|
||||
|
||||
// dispatchCalendarEvents maps one person's assignments to calendar events. The
|
||||
// service time is a wall-clock time in the parish, so the event is built with
|
||||
// the server's local zone and stays a floating local time in the .ics file.
|
||||
func dispatchCalendarEvents(assignments []dispatchAssignmentView) []domain.CalendarEvent {
|
||||
events := make([]domain.CalendarEvent, 0, len(assignments))
|
||||
for _, assignment := range assignments {
|
||||
start := time.Date(
|
||||
assignment.Date.Year(), assignment.Date.Month(), assignment.Date.Day(),
|
||||
assignment.SortMinutes/60, assignment.SortMinutes%60, 0, 0, time.Local,
|
||||
)
|
||||
events = append(events, domain.CalendarEvent{
|
||||
UID: assignment.ID, Start: start, DurationMinutes: 60,
|
||||
Summary: assignment.Title, Location: assignment.Place,
|
||||
Description: "Dienst: " + assignment.RoleLabel,
|
||||
})
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
func (s *Server) dispatchPeople(ctx context.Context, tenantID string, rows []domain.DayPlanRow) ([]dispatchPersonView, error) {
|
||||
people, err := s.store.People(ctx, tenantID)
|
||||
if err != nil {
|
||||
@@ -280,11 +320,11 @@ func (s *Server) handleDispatch(w http.ResponseWriter, r *http.Request, user *st
|
||||
return
|
||||
}
|
||||
config := s.loadSMTPConfig(r.Context(), tenant.ID)
|
||||
intro, greeting := s.dispatchTexts(r.Context(), tenant.ID)
|
||||
intro, greeting := s.dispatchTexts(r.Context(), tenant.ID, user.ID)
|
||||
subject := "Gottesdienstplan " + rng.ShortTitle() + " · " + tenant.Name
|
||||
for index := range people {
|
||||
people[index].AssignmentText = emailAssignmentTable(people[index].Assignments)
|
||||
people[index].MailText = dispatchEmailBody(intro, greeting, rng, people[index].Assignments)
|
||||
people[index].MailText = dispatchEmailBody(intro, greeting, rng, people[index].Assignments, false)
|
||||
if email := strings.TrimSpace(people[index].Person.Email); email != "" {
|
||||
people[index].Mailto = dispatchMailto(email, subject, people[index].MailText)
|
||||
}
|
||||
@@ -363,12 +403,15 @@ func (s *Server) dispatchFormFromRequest(r *http.Request, people []domain.Person
|
||||
return form
|
||||
}
|
||||
|
||||
func (s *Server) saveDispatchForm(r *http.Request, tenantID string, form dispatchForm) error {
|
||||
// An emptied intro field resets the default wording.
|
||||
if err := s.store.SetTenantSetting(r.Context(), tenantID, dispatchIntroKey, form.Intro); err != nil {
|
||||
func (s *Server) saveDispatchForm(r *http.Request, tenantID, userID string, form dispatchForm) error {
|
||||
// An emptied intro field resets the default wording. The text is stored per
|
||||
// editor so it is reused the next time this account opens the dispatch page.
|
||||
if err := s.store.SetTenantSetting(r.Context(), tenantID,
|
||||
dispatchUserKey(dispatchUserIntroKey, userID), form.Intro); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.store.SetTenantSetting(r.Context(), tenantID, dispatchGreetingKey, form.Greeting); err != nil {
|
||||
if err := s.store.SetTenantSetting(r.Context(), tenantID,
|
||||
dispatchUserKey(dispatchUserGreetingKey, userID), form.Greeting); err != nil {
|
||||
return err
|
||||
}
|
||||
for personID, selection := range form.Selections {
|
||||
@@ -392,7 +435,7 @@ func (s *Server) handleDispatchSave(w http.ResponseWriter, r *http.Request, user
|
||||
return
|
||||
}
|
||||
form := s.dispatchFormFromRequest(r, people)
|
||||
if err := s.saveDispatchForm(r, tenant.ID, form); err != nil {
|
||||
if err := s.saveDispatchForm(r, tenant.ID, user.ID, form); err != nil {
|
||||
s.setFlash(w, "Die Versendung konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
} else {
|
||||
s.setFlash(w, "Versendung gespeichert.", "success")
|
||||
@@ -452,15 +495,21 @@ func emailAssignmentTable(assignments []dispatchAssignmentView) string {
|
||||
return strings.TrimRight(buffer.String(), "\n")
|
||||
}
|
||||
|
||||
func dispatchEmailBody(intro, greeting string, rng domain.DayRange, assignments []dispatchAssignmentView) string {
|
||||
func dispatchEmailBody(intro, greeting string, rng domain.DayRange, assignments []dispatchAssignmentView, withAttachmentHint bool) string {
|
||||
parts := []string{resolveDispatchText(intro, rng)}
|
||||
parts = append(parts, "Ihre Einsätze im Zeitraum:\n\n"+emailAssignmentTable(assignments))
|
||||
if withAttachmentHint {
|
||||
parts = append(parts, attachmentHint)
|
||||
}
|
||||
if strings.TrimSpace(greeting) != "" {
|
||||
parts = append(parts, resolveDispatchText(greeting, rng))
|
||||
}
|
||||
return strings.Join(parts, "\n\n")
|
||||
}
|
||||
|
||||
const attachmentHint = "Im Anhang finden Sie den Plan als PDF sowie eine Kalenderdatei (.ics), " +
|
||||
"die Sie in Ihren Kalender importieren können."
|
||||
|
||||
// dispatchMailto builds a draft link for the local mail client. It is used
|
||||
// when no SMTP account has been configured.
|
||||
func dispatchMailto(email, subject, body string) string {
|
||||
@@ -485,7 +534,7 @@ func (s *Server) handleDispatchSend(w http.ResponseWriter, r *http.Request, user
|
||||
return
|
||||
}
|
||||
form := s.dispatchFormFromRequest(r, people)
|
||||
if err := s.saveDispatchForm(r, tenant.ID, form); err != nil {
|
||||
if err := s.saveDispatchForm(r, tenant.ID, user.ID, form); err != nil {
|
||||
s.setFlash(w, "Der Versand konnte nicht vorbereitet werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/dispatch?start="+domain.Key(form.Range.Start)+"&end="+domain.Key(form.Range.End))
|
||||
return
|
||||
@@ -508,6 +557,7 @@ func (s *Server) handleDispatchSend(w http.ResponseWriter, r *http.Request, user
|
||||
}
|
||||
batchID := domain.NewID()
|
||||
now := time.Now().UTC()
|
||||
calendarName := "Gottesdienstplan " + tenant.Name
|
||||
attachments := map[string][]byte{}
|
||||
sent, failed, fallback := 0, 0, 0
|
||||
var firstError string
|
||||
@@ -538,11 +588,22 @@ func (s *Server) handleDispatchSend(w http.ResponseWriter, r *http.Request, user
|
||||
attachments[selection.Variant] = document
|
||||
}
|
||||
assignments := dispatchAssignments(rows, person.ID)
|
||||
body := dispatchEmailBody(form.Intro, form.Greeting, form.Range, assignments)
|
||||
body := dispatchEmailBody(form.Intro, form.Greeting, form.Range, assignments, true)
|
||||
subject := "Gottesdienstplan " + form.Range.ShortTitle() + " · " + tenant.Name
|
||||
filename := fmt.Sprintf("LektorenPlan-%s-%s-%s.pdf", tenant.Slug,
|
||||
normalizeDispatchVariant(selection.Variant), domain.Key(form.Range.Start))
|
||||
err := sendMail(config, person.Email, subject, body, attachments[selection.Variant], filename)
|
||||
// The calendar file only contains this recipient's assignments, so it is
|
||||
// generated per person instead of being cached like the plan PDF.
|
||||
calendar := domain.CalendarICS(calendarName, dispatchCalendarEvents(assignments))
|
||||
files := []mailAttachment{
|
||||
{Name: filename, ContentType: "application/pdf", Data: attachments[selection.Variant]},
|
||||
{
|
||||
Name: domain.CalendarFilename(tenant.Slug, domain.Key(form.Range.Start)),
|
||||
ContentType: "text/calendar; charset=utf-8; method=PUBLISH",
|
||||
Data: []byte(calendar),
|
||||
},
|
||||
}
|
||||
err := sendMail(config, person.Email, subject, body, files)
|
||||
entry := store.DispatchLogEntry{
|
||||
TenantID: tenant.ID, BatchID: batchID, RangeStart: form.Range.Start,
|
||||
RangeEnd: form.Range.End, PersonID: person.ID, PersonName: person.FullName(),
|
||||
@@ -597,7 +658,7 @@ func (s *Server) handleDispatchPrint(w http.ResponseWriter, r *http.Request, use
|
||||
return
|
||||
}
|
||||
form := s.dispatchFormFromRequest(r, people)
|
||||
if err := s.saveDispatchForm(r, tenant.ID, form); err != nil {
|
||||
if err := s.saveDispatchForm(r, tenant.ID, user.ID, form); err != nil {
|
||||
s.setFlash(w, "Die Druckliste konnte nicht vorbereitet werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/dispatch?start="+domain.Key(form.Range.Start)+"&end="+domain.Key(form.Range.End))
|
||||
return
|
||||
|
||||
@@ -78,11 +78,27 @@ func TestDispatchPageAndPreferences(t *testing.T) {
|
||||
if preference.Channel != "print" || preference.Variant != "full" || !preference.Cover {
|
||||
t.Fatalf("unexpected preference: %+v", preference)
|
||||
}
|
||||
if got := st.TenantSetting(ctx, tenantID, dispatchIntroKey); !strings.Contains(got, "{start}") {
|
||||
t.Fatalf("intro setting = %q", got)
|
||||
if got := st.TenantSetting(ctx, tenantID, dispatchIntroKey); got != "" {
|
||||
t.Fatalf("legacy intro setting should stay untouched, got %q", got)
|
||||
}
|
||||
if got := st.TenantSetting(ctx, tenantID, dispatchGreetingKey); got != "Mit Grüßen" {
|
||||
t.Fatalf("greeting setting = %q", got)
|
||||
editor, err := st.UserByUsername(ctx, "editor")
|
||||
if err != nil || editor == nil {
|
||||
t.Fatalf("editor account: %v", err)
|
||||
}
|
||||
if got := st.TenantSetting(ctx, tenantID, dispatchUserKey(dispatchUserIntroKey, editor.ID)); !strings.Contains(got, "{start}") {
|
||||
t.Fatalf("per-editor intro setting = %q", got)
|
||||
}
|
||||
if got := st.TenantSetting(ctx, tenantID, dispatchUserKey(dispatchUserGreetingKey, editor.ID)); got != "Mit Grüßen" {
|
||||
t.Fatalf("per-editor greeting setting = %q", got)
|
||||
}
|
||||
|
||||
// Reopening the page reuses the text saved for this editor account.
|
||||
reloaded := get(t, client, ts.URL+"/dispatch?"+dispatchRange, http.StatusOK)
|
||||
if !strings.Contains(reloaded, "Liebe Leute, anbei der Plan von") {
|
||||
t.Fatal("saved intro text is not reused on the next page load")
|
||||
}
|
||||
if !strings.Contains(reloaded, "Mit Grüßen") {
|
||||
t.Fatal("saved greeting is not reused on the next page load")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+23
-8
@@ -26,6 +26,14 @@ type smtpConfig struct {
|
||||
Encryption string
|
||||
}
|
||||
|
||||
// mailAttachment is one MIME attachment. ContentType must include the media
|
||||
// type, for example "application/pdf" or "text/calendar; charset=utf-8".
|
||||
type mailAttachment struct {
|
||||
Name string
|
||||
ContentType string
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func (c smtpConfig) configured() bool {
|
||||
return strings.TrimSpace(c.Host) != "" && strings.TrimSpace(c.FromAddress) != ""
|
||||
}
|
||||
@@ -86,7 +94,7 @@ func encodeBase64Lines(value []byte) string {
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func buildMailMessage(config smtpConfig, to, subject, body string, attachment []byte, attachmentName string) []byte {
|
||||
func buildMailMessage(config smtpConfig, to, subject, body string, attachments []mailAttachment) []byte {
|
||||
boundary := randomBoundary()
|
||||
var message bytes.Buffer
|
||||
message.WriteString("From: " + config.sender() + "\r\n")
|
||||
@@ -103,16 +111,23 @@ func buildMailMessage(config smtpConfig, to, subject, body string, attachment []
|
||||
message.WriteString(encodeBase64Lines([]byte(body)))
|
||||
message.WriteString("\r\n")
|
||||
|
||||
if len(attachment) > 0 {
|
||||
name := sanitizeHeader(attachmentName)
|
||||
for _, attachment := range attachments {
|
||||
if len(attachment.Data) == 0 {
|
||||
continue
|
||||
}
|
||||
name := sanitizeHeader(attachment.Name)
|
||||
if name == "" {
|
||||
name = "Gottesdienstplan.pdf"
|
||||
name = "Anhang"
|
||||
}
|
||||
contentType := sanitizeHeader(attachment.ContentType)
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
message.WriteString("--" + boundary + "\r\n")
|
||||
message.WriteString("Content-Type: application/pdf; name=\"" + name + "\"\r\n")
|
||||
message.WriteString("Content-Type: " + contentType + "; name=\"" + name + "\"\r\n")
|
||||
message.WriteString("Content-Transfer-Encoding: base64\r\n")
|
||||
message.WriteString("Content-Disposition: attachment; filename=\"" + name + "\"\r\n\r\n")
|
||||
message.WriteString(encodeBase64Lines(attachment))
|
||||
message.WriteString(encodeBase64Lines(attachment.Data))
|
||||
message.WriteString("\r\n")
|
||||
}
|
||||
|
||||
@@ -120,7 +135,7 @@ func buildMailMessage(config smtpConfig, to, subject, body string, attachment []
|
||||
return message.Bytes()
|
||||
}
|
||||
|
||||
func sendMail(config smtpConfig, to, subject, body string, attachment []byte, attachmentName string) error {
|
||||
func sendMail(config smtpConfig, to, subject, body string, attachments []mailAttachment) error {
|
||||
if !config.configured() {
|
||||
return fmt.Errorf("SMTP ist noch nicht konfiguriert")
|
||||
}
|
||||
@@ -186,7 +201,7 @@ func sendMail(config smtpConfig, to, subject, body string, attachment []byte, at
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := writer.Write(buildMailMessage(config, recipient.Address, subject, body, attachment, attachmentName)); err != nil {
|
||||
if _, err := writer.Write(buildMailMessage(config, recipient.Address, subject, body, attachments)); err != nil {
|
||||
writer.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
+13
-4
@@ -7,18 +7,22 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBuildMailMessageCarriesTextAndPDF(t *testing.T) {
|
||||
func TestBuildMailMessageCarriesTextPDFAndCalendar(t *testing.T) {
|
||||
config := smtpConfig{
|
||||
Host: "smtp.example.org",
|
||||
Port: 587,
|
||||
FromAddress: "plan@example.org",
|
||||
FromName: "Pfarrei Sankt Michael",
|
||||
}
|
||||
attachment := []byte("%PDF-1.4\nfake dispatch packet\n%%EOF")
|
||||
pdf := []byte("%PDF-1.4\nfake dispatch packet\n%%EOF")
|
||||
calendar := []byte("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nEND:VCALENDAR\r\n")
|
||||
subject := "Gottesdienstplan März 2026 · Pfarrei"
|
||||
body := "Hallo Anna"
|
||||
|
||||
raw := buildMailMessage(config, "anna@example.org", subject, body, attachment, "Plan.pdf")
|
||||
raw := buildMailMessage(config, "anna@example.org", subject, body, []mailAttachment{
|
||||
{Name: "Plan.pdf", ContentType: "application/pdf", Data: pdf},
|
||||
{Name: "Kalender.ics", ContentType: "text/calendar; charset=utf-8; method=PUBLISH", Data: calendar},
|
||||
})
|
||||
|
||||
message, err := mail.ReadMessage(strings.NewReader(string(raw)))
|
||||
if err != nil {
|
||||
@@ -38,16 +42,21 @@ func TestBuildMailMessageCarriesTextAndPDF(t *testing.T) {
|
||||
for _, want := range []string{
|
||||
"Content-Type: text/plain; charset=utf-8",
|
||||
"Content-Type: application/pdf",
|
||||
"Content-Type: text/calendar; charset=utf-8; method=PUBLISH",
|
||||
`filename="Plan.pdf"`,
|
||||
`filename="Kalender.ics"`,
|
||||
"Content-Disposition: attachment",
|
||||
} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Fatalf("message misses %q", want)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(text, base64.StdEncoding.EncodeToString(attachment)) {
|
||||
if !strings.Contains(text, base64.StdEncoding.EncodeToString(pdf)) {
|
||||
t.Fatal("PDF attachment is not base64 encoded in the message")
|
||||
}
|
||||
if !strings.Contains(text, base64.StdEncoding.EncodeToString(calendar)) {
|
||||
t.Fatal("calendar attachment is not base64 encoded in the message")
|
||||
}
|
||||
if !strings.Contains(text, base64.StdEncoding.EncodeToString([]byte(body))) {
|
||||
t.Fatal("mail body is not base64 encoded in the message")
|
||||
}
|
||||
|
||||
@@ -75,9 +75,9 @@
|
||||
</div>
|
||||
<div class="settings-grid">
|
||||
<div class="settings-copy">
|
||||
<h4>Ein Text für alle</h4>
|
||||
<p>Der Einleitungstext erscheint in jeder E-Mail und als Vorblatt im Ausdruck. Zwischen Einleitung und Abschluss wird automatisch die Einsatzübersicht der jeweiligen Person eingefügt. Die Platzhalter <code>{start}</code> und <code>{end}</code> werden beim Versand durch den Planungszeitraum ersetzt.</p>
|
||||
<p class="muted">Ein leer gelassenes Einleitungsfeld stellt den Standardtext wieder her. Über das Kopier-Symbol lässt sich der aktuelle Text in die Zwischenablage übernehmen.</p>
|
||||
<h4>Ihr Text für alle</h4>
|
||||
<p>Der Einleitungstext erscheint in jeder E-Mail und als Vorblatt im Ausdruck. Zwischen Einleitung und Abschluss wird automatisch die Einsatzübersicht der jeweiligen Person sowie ein Hinweis auf die beiden Anhänge (PDF-Plan und Kalenderdatei) eingefügt. Die Platzhalter <code>{start}</code> und <code>{end}</code> werden beim Versand durch den Planungszeitraum ersetzt.</p>
|
||||
<p class="muted">Ihr Text wird für Ihr Redakteurskonto gespeichert und beim nächsten Aufruf wieder eingesetzt. Ein leer gelassenes Einleitungsfeld stellt den Standardtext wieder her. Über das Kopier-Symbol lässt sich der aktuelle Text in die Zwischenablage übernehmen.</p>
|
||||
</div>
|
||||
<div class="settings-fields">
|
||||
<label class="field"><span class="field-label">Einleitungstext</span>
|
||||
@@ -176,7 +176,7 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="table-note">E-Mail-Empfänger erhalten den Plan als PDF-Anhang. Personen ohne Adresse oder mit der Auswahl „Ausdruck“ werden in einem sammelbaren PDF zusammengefasst – nacheinander mit Vorblatt und gewählter Liste. In der Spalte „Text“ kopiert das erste Symbol das persönliche Anschreiben; ohne SMTP öffnet das zweite Symbol einen fertigen Entwurf im eigenen E-Mail-Programm.{{if not .Data.CanManageSecrets}} Empfängeradressen und SMTP-Zugangsdaten sind für dieses Konto gesperrt und werden von Redakteuren verwaltet.{{end}}</p>
|
||||
<p class="table-note">E-Mail-Empfänger erhalten den Plan als PDF-Anhang und zusätzlich eine Kalenderdatei (.ics) mit ihren eigenen Einsätzen zum Import in gängige Kalender-Apps. Personen ohne Adresse oder mit der Auswahl „Ausdruck“ werden in einem sammelbaren PDF zusammengefasst – nacheinander mit Vorblatt und gewählter Liste. In der Spalte „Text“ kopiert das erste Symbol das persönliche Anschreiben; ohne SMTP öffnet das zweite Symbol einen fertigen Entwurf im eigenen E-Mail-Programm.{{if not .Data.CanManageSecrets}} Empfängeradressen und SMTP-Zugangsdaten sind für dieses Konto gesperrt und werden von Redakteuren verwaltet.{{end}}</p>
|
||||
<div class="card-foot dispatch-actions">
|
||||
<button class="btn btn-secondary" type="submit">{{icon "check"}} Auswahl speichern</button>
|
||||
{{if .Data.SMTPConfigured}}
|
||||
|
||||
Reference in new issue
Block a user