1. Version Versendung

This commit is contained in:
concierge committed 2026-11-14 09:33:17 +01:00
1 parent d7113afa5f
commit 781aa20253
31 files changed
+4023 -10

No files matched your search

@@ -0,0 +1,367 @@
import AppKit
import CoreGraphics
import LektorenPlanCore
/// One assignment of a recipient, as shown on the cover sheet.
struct DispatchAssignment: Identifiable, Hashable {
var id: String
var date: Date
var timeMinutes: Int
var church: String
var title: String
var role: Role
var dateLabel: String {
"\(DayMath.shortWeekdayName(date)), \(DayMath.dayNumber(date)).\(DayMath.month(date)).\(DayMath.year(date))"
}
var timeLabel: String {
DayMath.timeString(minutes: timeMinutes)
}
}
/// Data for the personal cover letter that precedes a printed plan.
struct DispatchCoverData {
var range: DayRange
var person: Person
var intro: String
var greeting: String
var assignments: [DispatchAssignment]
var generatedAt: Date
}
/// Renders the personalized A4 cover sheet for dispatch packets.
enum DispatchCoverPDFRenderer {
private static let pageWidth: CGFloat = 595
private static let pageHeight: CGFloat = 842
private static let margin: CGFloat = 48
private static let contentWidth: CGFloat = pageWidth - margin * 2
private static let footerHeight: CGFloat = 30
private static let contentBottom: CGFloat = pageHeight - margin - footerHeight
// MARK: - Colours
private static let ink = NSColor(calibratedRed: 0.12, green: 0.135, blue: 0.155, alpha: 1)
private static let secondaryInk = NSColor(calibratedRed: 0.38, green: 0.385, blue: 0.39, alpha: 1)
private static let tertiaryInk = NSColor(calibratedRed: 0.52, green: 0.51, blue: 0.49, alpha: 1)
private static let lineColor = NSColor(calibratedRed: 0.845, green: 0.825, blue: 0.79, alpha: 1)
private static let accent = NSColor(calibratedRed: 0.18, green: 0.36, blue: 0.34, alpha: 1)
private static let headerWash = NSColor(calibratedRed: 0.965, green: 0.945, blue: 0.905, alpha: 1)
// MARK: - Fonts
private static func serif(_ size: CGFloat, bold: Bool = false) -> NSFont {
let name = bold ? "NewYork-Semibold" : "NewYork-Regular"
return NSFont(name: name, size: size) ?? NSFont.systemFont(ofSize: size, weight: bold ? .semibold : .regular)
}
private static func sans(_ size: CGFloat, weight: NSFont.Weight = .regular) -> NSFont {
NSFont.systemFont(ofSize: size, weight: weight)
}
// MARK: - Render
static func render(_ data: DispatchCoverData) -> Data {
let output = NSMutableData()
var mediaBox = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
guard let consumer = CGDataConsumer(data: output as CFMutableData),
let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)
else { return Data() }
storedContext = context
defer { storedContext = nil }
var pageIndex = 0
func beginPage() {
context.beginPDFPage(nil)
context.saveGState()
context.translateBy(x: 0, y: pageHeight)
context.scaleBy(x: 1, y: -1)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
}
func endPage() {
drawText(
"LektorenPlan · \(data.person.fullName) · \(data.range.shortTitle)",
in: CGRect(x: margin, y: pageHeight - margin + 6, width: contentWidth, height: 10),
font: sans(6.5),
color: tertiaryInk
)
drawText(
"Seite \(pageIndex + 1)",
in: CGRect(x: margin, y: pageHeight - margin + 6, width: contentWidth, height: 10),
font: sans(6.5),
color: tertiaryInk,
alignment: .right
)
NSGraphicsContext.restoreGraphicsState()
context.restoreGState()
context.endPDFPage()
pageIndex += 1
}
beginPage()
var cursorY = margin
// Header ------------------------------------------------------------
drawText(
"LEKTORENPLAN · GOTTESDIENSTPLAN",
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 10),
font: sans(7, weight: .bold),
color: accent
)
cursorY += 8
drawText(
"Gottesdienstplan",
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 26),
font: serif(20, bold: true),
color: ink
)
cursorY += 24
drawText(
data.range.title,
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 14),
font: sans(10),
color: secondaryInk
)
cursorY += 20
context.setStrokeColor(lineColor.cgColor)
context.setLineWidth(0.8)
context.move(to: CGPoint(x: margin, y: cursorY))
context.addLine(to: CGPoint(x: pageWidth - margin, y: cursorY))
context.strokePath()
cursorY += 22
// Recipient ---------------------------------------------------------
drawText(
"EMPFÄNGER",
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 9),
font: sans(6.5, weight: .bold),
color: tertiaryInk
)
cursorY += 10
drawText(
data.person.fullName,
in: CGRect(x: margin, y: cursorY, width: contentWidth - 150, height: 19),
font: serif(13, bold: true),
color: ink
)
drawText(
"Erstellt am \(DayMath.longString(data.generatedAt))",
in: CGRect(x: margin, y: cursorY + 3, width: contentWidth, height: 12),
font: sans(7.5),
color: tertiaryInk,
alignment: .right
)
cursorY += 18
if !data.person.email.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
drawText(
data.person.email,
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 12),
font: sans(8),
color: secondaryInk
)
cursorY += 14
}
cursorY += 14
// Letter text -------------------------------------------------------
let introFont = serif(11.5)
let introLineHeight: CGFloat = 16
for line in wrappedLines(data.intro, font: introFont, width: contentWidth) {
if cursorY + introLineHeight > contentBottom {
endPage()
beginPage()
cursorY = margin
}
drawText(
line,
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: introLineHeight),
font: introFont,
color: ink
)
cursorY += introLineHeight
}
cursorY += 14
// Assignment table --------------------------------------------------
if cursorY + 70 > contentBottom {
endPage()
beginPage()
cursorY = margin
}
drawText(
"Ihre Einsätze im Planungszeitraum",
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 18),
font: serif(12.5, bold: true),
color: ink
)
cursorY += 21
let columns: [(title: String, width: CGFloat)] = [
("Tag", 150), ("Zeit", 54), ("Ort", 120), ("Dienst", contentWidth - 150 - 54 - 120)
]
if data.assignments.isEmpty {
for line in wrappedLines(
"Für Sie sind in diesem Zeitraum keine Einsätze eingetragen.",
font: serif(10.5),
width: contentWidth
) {
if cursorY + 14 > contentBottom {
endPage()
beginPage()
cursorY = margin
}
drawText(line, in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 14),
font: serif(10.5), color: secondaryInk)
cursorY += 14
}
cursorY += 8
} else {
contextFill(CGRect(x: margin, y: cursorY, width: contentWidth, height: 16), color: headerWash)
var columnX = margin + 4
for column in columns {
drawText(
column.title.uppercased(),
in: CGRect(x: columnX, y: cursorY + 4, width: column.width - 6, height: 9),
font: sans(6.4, weight: .bold),
color: tertiaryInk
)
columnX += column.width
}
cursorY += 16
contextLine(y: cursorY)
for assignment in data.assignments {
if cursorY + 18 > contentBottom {
endPage()
beginPage()
cursorY = margin
}
let values = [
assignment.dateLabel,
assignment.timeLabel,
assignment.church,
"\(assignment.role.title) · \(assignment.title)"
]
columnX = margin + 4
for (index, column) in columns.enumerated() {
drawText(
values[index],
in: CGRect(x: columnX, y: cursorY + 4.5, width: column.width - 6, height: 12),
font: sans(7.8),
color: ink
)
columnX += column.width
}
cursorY += 18
context.setStrokeColor(lineColor.withAlphaComponent(0.65).cgColor)
context.setLineWidth(0.4)
context.move(to: CGPoint(x: margin, y: cursorY))
context.addLine(to: CGPoint(x: pageWidth - margin, y: cursorY))
context.strokePath()
}
cursorY += 14
}
// Greeting ----------------------------------------------------------
if !data.greeting.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
for line in wrappedLines(data.greeting, font: introFont, width: contentWidth) {
if cursorY + introLineHeight > contentBottom {
endPage()
beginPage()
cursorY = margin
}
drawText(
line,
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: introLineHeight),
font: introFont,
color: ink
)
cursorY += introLineHeight
}
}
endPage()
context.closePDF()
return output as Data
}
// MARK: - Text helpers
private static func wrappedLines(_ text: String, font: NSFont, width: CGFloat) -> [String] {
let paragraphs = text.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
var lines: [String] = []
for paragraph in paragraphs {
let trimmed = paragraph.trimmingCharacters(in: .whitespaces)
if trimmed.isEmpty {
lines.append("")
continue
}
var current = ""
for word in trimmed.split(separator: " ", omittingEmptySubsequences: true) {
let candidate = current.isEmpty ? String(word) : current + " " + word
if measure(candidate, font: font) <= width {
current = candidate
} else {
if !current.isEmpty { lines.append(current) }
current = String(word)
}
}
if !current.isEmpty { lines.append(current) }
}
return lines
}
private static func measure(_ text: String, font: NSFont) -> CGFloat {
(text as NSString).size(withAttributes: [.font: font]).width
}
@discardableResult
private static func drawText(
_ text: String,
in rect: CGRect,
font: NSFont,
color: NSColor,
alignment: NSTextAlignment = .left
) -> CGFloat {
guard !text.isEmpty else { return 0 }
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = alignment
paragraph.lineBreakMode = .byTruncatingTail
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: color,
.paragraphStyle: paragraph
]
NSAttributedString(string: text, attributes: attributes).draw(
with: CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height),
options: [.usesLineFragmentOrigin, .usesFontLeading]
)
return rect.height
}
private static func contextLine(y: CGFloat) {
context.setStrokeColor(lineColor.withAlphaComponent(0.85).cgColor)
context.setLineWidth(0.6)
context.move(to: CGPoint(x: margin, y: y))
context.addLine(to: CGPoint(x: pageWidth - margin, y: y))
context.strokePath()
}
private static func contextFill(_ rect: CGRect, color: NSColor) {
context.setFillColor(color.cgColor)
context.fill(rect)
}
nonisolated(unsafe) private static var storedContext: CGContext?
private static var context: CGContext {
storedContext ?? CGContext(data: nil, width: 1, height: 1, bitsPerComponent: 8,
bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
}
}
+22
View File
@@ -0,0 +1,22 @@
import Foundation
import PDFKit
/// Concatenates several PDF documents page by page. Used for the printable
/// dispatch packet: cover sheet and selected list for each recipient.
enum PDFMerger {
static func merge(_ documents: [Data]) -> Data {
let output = PDFDocument()
for data in documents {
guard let document = PDFDocument(data: data) else { continue }
for index in 0..<document.pageCount {
guard let page = document.page(at: index) else { continue }
output.insert(page, at: output.pageCount)
}
}
return output.dataRepresentation() ?? Data()
}
static func pageCount(_ data: Data) -> Int {
PDFDocument(data: data)?.pageCount ?? 0
}
}
+361 -2
View File
@@ -9,6 +9,7 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable {
case serviceOrder case serviceOrder
case team case team
case statistics case statistics
case dispatch
case exchange case exchange
case settings case settings
@@ -20,6 +21,7 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable {
case .serviceOrder: "Gottesdienstordnung" case .serviceOrder: "Gottesdienstordnung"
case .team: "Lektoren & Helfer" case .team: "Lektoren & Helfer"
case .statistics: "Statistik" case .statistics: "Statistik"
case .dispatch: "Versendung"
case .exchange: "Austausch" case .exchange: "Austausch"
case .settings: "Einstellungen" case .settings: "Einstellungen"
} }
@@ -31,6 +33,7 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable {
case .serviceOrder: "Ordnung" case .serviceOrder: "Ordnung"
case .team: "Team" case .team: "Team"
case .statistics: "Statistik" case .statistics: "Statistik"
case .dispatch: "Versendung"
case .exchange: "Austausch" case .exchange: "Austausch"
case .settings: "Einstellungen" case .settings: "Einstellungen"
} }
@@ -42,6 +45,7 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable {
case .serviceOrder: "building.columns" case .serviceOrder: "building.columns"
case .team: "person.2" case .team: "person.2"
case .statistics: "chart.xyaxis.line" case .statistics: "chart.xyaxis.line"
case .dispatch: "paperplane"
case .exchange: "arrow.left.arrow.right" case .exchange: "arrow.left.arrow.right"
case .settings: "gearshape" case .settings: "gearshape"
} }
@@ -53,8 +57,9 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable {
case .serviceOrder: 2 case .serviceOrder: 2
case .team: 3 case .team: 3
case .statistics: 4 case .statistics: 4
case .exchange: 5 case .dispatch: 5
case .settings: 6 case .exchange: 6
case .settings: 7
} }
} }
} }
@@ -144,8 +149,28 @@ struct CandidateSuggestion: Identifiable {
var id: String { person.id } var id: String { person.id }
} }
struct DispatchRecipient: Identifiable {
var person: Person
var preference: DispatchPreference
var assignments: [DispatchAssignment]
var id: String { person.id }
var effectiveChannel: DispatchChannel { preference.effectiveChannel(for: person) }
var hasEmail: Bool { !person.email.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
}
@MainActor @MainActor
final class PlanModel: ObservableObject { final class PlanModel: ObservableObject {
static let defaultDispatchIntro = """
Liebe Lektorinnen und Lektoren, liebe Kommunionhelferinnen und -helfer,
anbei sende ich den Plan für den Zeitraum von {start} bis {end}. Dabei konnten hoffentlich alle Wünsche und Termine berücksichtigt werden.
"""
static let defaultDispatchGreeting = """
Mit freundlichen Grüßen
Ihr Pfarreiteam
"""
let db: AppDatabase let db: AppDatabase
@Published var section: AppSection = .planning @Published var section: AppSection = .planning
@@ -183,6 +208,10 @@ final class PlanModel: ObservableObject {
@Published var databasePath: String @Published var databasePath: String
@Published var startupWarning: String? @Published var startupWarning: String?
@Published var isResettingData = false @Published var isResettingData = false
@Published var dispatchPreferences: [String: DispatchPreference] = [:]
@Published var dispatchLog: [DispatchLogEntry] = []
@Published var dispatchIntro: String = PlanModel.defaultDispatchIntro
@Published var dispatchGreeting: String = PlanModel.defaultDispatchGreeting
private var toastTask: Task<Void, Never>? private var toastTask: Task<Void, Never>?
@@ -217,6 +246,7 @@ final class PlanModel: ObservableObject {
self.showOnlySundaysAndFeasts = value == "1" self.showOnlySundaysAndFeasts = value == "1"
} }
loadAll() loadAll()
loadDispatch()
if let warning { alertMessage = warning; alertTitle = "Eingeschränkter Betrieb" } if let warning { alertMessage = warning; alertTitle = "Eingeschränkter Betrieb" }
} }
@@ -829,6 +859,7 @@ final class PlanModel: ObservableObject {
let summary = try db.applyPlanExchange(preview.exchange) let summary = try db.applyPlanExchange(preview.exchange)
importPreview = nil importPreview = nil
loadAll() loadAll()
loadDispatch()
showToast("Import abgeschlossen: \(summary.services) Gottesdienste, \(summary.assignments) Einsätze, \(summary.people) Personen.", kind: .success) showToast("Import abgeschlossen: \(summary.services) Gottesdienste, \(summary.assignments) Einsätze, \(summary.people) Personen.", kind: .success)
} catch { } catch {
alertTitle = "Import fehlgeschlagen" alertTitle = "Import fehlgeschlagen"
@@ -922,6 +953,333 @@ final class PlanModel: ObservableObject {
} }
} }
// MARK: - Dispatch
/// Recipients for the current planning period, including their effective
/// channel and personal assignment overview.
var dispatchRecipients: [DispatchRecipient] {
people
.filter(\.active)
.map { person in
dispatchRecipientsWithAssignments(for: person)
}
}
private func dispatchRecipientsWithAssignments(for person: Person) -> DispatchRecipient {
var preference = dispatchPreferences[person.id]
?? DispatchPreference(channel: person.email.isEmpty ? .print : .email)
if preference.channel == .email && person.email.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
preference.channel = .print
}
return DispatchRecipient(
person: person,
preference: preference,
assignments: dispatchAssignments(for: person.id)
)
}
func dispatchPreference(for person: Person) -> DispatchPreference {
dispatchRecipientsWithAssignments(for: person).preference
}
func setDispatchChannel(_ channel: DispatchChannel, for person: Person) {
var preference = dispatchPreference(for: person)
preference.channel = channel
dispatchPreferences[person.id] = preference
}
func setDispatchVariant(_ variant: PlanListVariant, for person: Person) {
var preference = dispatchPreference(for: person)
preference.variant = variant
dispatchPreferences[person.id] = preference
}
func setDispatchCover(_ cover: Bool, for person: Person) {
var preference = dispatchPreference(for: person)
preference.cover = cover
dispatchPreferences[person.id] = preference
}
func setDispatchChannelForAll(_ channel: DispatchChannel) {
for recipient in dispatchRecipients {
setDispatchChannel(channel, for: recipient.person)
}
}
func dispatchAssignments(for personID: String) -> [DispatchAssignment] {
var result: [DispatchAssignment] = []
for row in rows {
for service in row.services {
for assignment in service.assignments where assignment.personID == personID {
result.append(DispatchAssignment(
id: assignment.id,
date: row.date,
timeMinutes: service.service.timeMinutes,
church: service.church.shortName,
title: service.service.title,
role: assignment.role
))
}
}
}
return result.sorted {
if $0.date != $1.date { return $0.date < $1.date }
return $0.timeMinutes < $1.timeMinutes
}
}
func loadDispatch() {
do {
dispatchPreferences = try db.dispatchPreferences()
dispatchLog = try db.dispatchLog()
} catch {
alertTitle = "Versendung konnte nicht geladen werden"
alertMessage = error.localizedDescription
}
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
}
/// 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)
for recipient in dispatchRecipients {
db.saveDispatchPreference(recipient.preference, personID: recipient.id)
}
refreshDispatchLog()
if showConfirmation {
showToast("Versendung gespeichert.", kind: .success)
}
}
func resolvedDispatchText(_ text: String) -> String {
text
.replacingOccurrences(of: "{start}", with: DayMath.mediumString(range.start))
.replacingOccurrences(of: "{end}", with: DayMath.mediumString(range.end))
.trimmingCharacters(in: .whitespacesAndNewlines)
}
func dispatchSubject() -> String {
"Gottesdienstplan \(range.shortTitle) · LektorenPlan"
}
func dispatchEmailBody(for recipient: DispatchRecipient) -> String {
var parts: [String] = [resolvedDispatchText(dispatchIntro)]
parts.append("Ihre Einsätze im Zeitraum:\n\n" + dispatchAssignmentLines(recipient.assignments))
let greeting = resolvedDispatchText(dispatchGreeting)
if !greeting.isEmpty {
parts.append(greeting)
}
return parts.joined(separator: "\n\n")
}
func dispatchAssignmentLines(_ assignments: [DispatchAssignment]) -> String {
guard !assignments.isEmpty else {
return "Für Sie sind in diesem Zeitraum keine Einsätze eingetragen."
}
return assignments
.map { "\($0.dateLabel) · \($0.timeLabel) · \($0.church) · \($0.role.title) · \($0.title)" }
.joined(separator: "\n")
}
/// Opens one Mail compose window per e-mail recipient, with the personal
/// text and the selected plan PDF attached.
func openDispatchEmails() {
let recipients = dispatchRecipients.filter { $0.effectiveChannel == .email }
guard !recipients.isEmpty else {
showToast("Keine Empfänger mit E-Mail-Adresse ausgewählt.", kind: .info)
return
}
saveDispatchSettings(showConfirmation: false)
let batchID = UUID().uuidString
let createdAt = Date()
let directory = dispatchTempDirectory()
var planCache: [PlanListVariant: Data] = [:]
var entries: [DispatchLogEntry] = []
var opened = 0
var failed = 0
var firstError = ""
for (index, recipient) in recipients.enumerated() {
let email = recipient.person.email.trimmingCharacters(in: .whitespacesAndNewlines)
func failure(_ reason: String) {
failed += 1
if firstError.isEmpty { firstError = reason }
entries.append(DispatchLogEntry(
batchID: batchID, rangeStart: range.start, rangeEnd: range.end,
personID: recipient.id, personName: recipient.person.fullName,
channel: .email, variant: recipient.preference.variant,
email: email, status: .failed, detail: reason, createdAt: createdAt
))
}
guard email.contains("@") else {
failure("Keine gültige E-Mail-Adresse")
continue
}
guard let service = NSSharingService(named: .composeEmail) else {
failure("Kein Mailprogramm verfügbar")
continue
}
let variant = recipient.preference.variant
if planCache[variant] == nil {
planCache[variant] = dispatchPlanData(variant: variant)
}
guard let planData = planCache[variant], !planData.isEmpty else {
failure("PDF konnte nicht erzeugt werden")
continue
}
let fileURL = directory.appendingPathComponent(dispatchFilename(for: recipient, variant: variant))
do {
try planData.write(to: fileURL, options: .atomic)
} catch {
failure("PDF 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])
}
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
))
}
persistDispatchLog(entries)
if failed == 0 {
showToast("\(opened) E-Mail-Entwürfe im Mailprogramm geöffnet.", kind: .success)
} else {
showToast("\(opened) Entwürfe geöffnet, \(failed) fehlgeschlagen. \(firstError)", kind: .info)
}
}
/// Builds one printable PDF: for each print recipient an optional cover
/// sheet followed by the selected plan variant.
func createDispatchPrintPDF() {
let recipients = dispatchRecipients.filter { $0.effectiveChannel == .print }
guard !recipients.isEmpty else {
showToast("Keine Empfänger für den Ausdruck ausgewählt.", kind: .info)
return
}
saveDispatchSettings(showConfirmation: false)
var planCache: [PlanListVariant: Data] = [:]
var documents: [Data] = []
for recipient in recipients {
if recipient.preference.cover {
let cover = DispatchCoverPDFRenderer.render(DispatchCoverData(
range: range,
person: recipient.person,
intro: resolvedDispatchText(dispatchIntro),
greeting: resolvedDispatchText(dispatchGreeting),
assignments: recipient.assignments,
generatedAt: Date()
))
if !cover.isEmpty { documents.append(cover) }
}
let variant = recipient.preference.variant
if planCache[variant] == nil {
planCache[variant] = dispatchPlanData(variant: variant)
}
if let planData = planCache[variant], !planData.isEmpty {
documents.append(planData)
}
}
let merged = PDFMerger.merge(documents)
guard !merged.isEmpty else {
alertTitle = "Versand-PDF nicht möglich"
alertMessage = "Die PDF-Dokumente konnten nicht zusammengeführt werden."
return
}
let batchID = UUID().uuidString
let createdAt = Date()
let entries = recipients.map { recipient in
DispatchLogEntry(
batchID: batchID, rangeStart: range.start, rangeEnd: range.end,
personID: recipient.id, personName: recipient.person.fullName,
channel: .print, variant: recipient.preference.variant,
cover: recipient.preference.cover, email: recipient.person.email,
status: .pdf,
detail: recipient.preference.cover ? "Mit Vorblatt" : "Ohne Vorblatt",
createdAt: createdAt
)
}
persistDispatchLog(entries)
pdfPreview = PDFPreview(
data: merged,
title: "Versand-PDF \(range.shortTitle)",
filename: "LektorenPlan_Versand_\(DayMath.key(range.start))_\(DayMath.key(range.end)).pdf",
formatLabel: "Sammel-PDF · \(recipients.count) Empfänger"
)
showToast("Versand-PDF für \(recipients.count) Empfänger erzeugt.", kind: .success)
}
var dispatchLastBatch: [DispatchLogEntry] {
guard let first = dispatchLog.first else { return [] }
return dispatchLog.prefix { $0.batchID == first.batchID }.map { $0 }
}
private func persistDispatchLog(_ entries: [DispatchLogEntry]) {
guard !entries.isEmpty else { return }
do {
try db.appendDispatchLog(entries)
} catch {
alertTitle = "Protokoll konnte nicht gespeichert werden"
alertMessage = error.localizedDescription
}
refreshDispatchLog()
}
private func refreshDispatchLog() {
dispatchLog = (try? db.dispatchLog()) ?? dispatchLog
}
private func dispatchPlanData(variant: PlanListVariant) -> Data {
switch variant {
case .full:
return PlanPDFRenderer.render(
range: range, rows: rows, churches: churches,
people: peopleByID, generatedAt: Date()
)
case .compact:
return CompactPlanPDFRenderer.render(
range: range, rows: rows, people: peopleByID, generatedAt: Date()
)
}
}
private func dispatchFilename(for recipient: DispatchRecipient, variant: PlanListVariant) -> String {
let base = 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 {
let manager = FileManager.default
let directory = manager.temporaryDirectory.appendingPathComponent("LektorenPlanVersand", isDirectory: true)
try? manager.createDirectory(at: directory, withIntermediateDirectories: true)
return directory
}
// MARK: - Demo // MARK: - Demo
func resetDemoData() { func resetDemoData() {
@@ -950,6 +1308,7 @@ final class PlanModel: ObservableObject {
db.setSetting("rangeStart", value: DayMath.key(range.start)) db.setSetting("rangeStart", value: DayMath.key(range.start))
db.setSetting("rangeEnd", value: DayMath.key(range.end)) db.setSetting("rangeEnd", value: DayMath.key(range.end))
loadAll() loadAll()
loadDispatch()
isResettingData = false isResettingData = false
showToast( showToast(
deleteOnly ? "Alle Daten wurden gelöscht." : "Demo-Daten neu aufgebaut.", deleteOnly ? "Alle Daten wurden gelöscht." : "Demo-Daten neu aufgebaut.",
+4
View File
@@ -84,6 +84,9 @@ struct RootView: View {
case .statistics: case .statistics:
StatisticsView() StatisticsView()
.transition(.opacity) .transition(.opacity)
case .dispatch:
DispatchView()
.transition(.opacity)
case .exchange: case .exchange:
ExchangeView() ExchangeView()
.transition(.opacity) .transition(.opacity)
@@ -115,6 +118,7 @@ private struct SidebarView: View {
sidebarRow(.serviceOrder) sidebarRow(.serviceOrder)
sidebarRow(.team, badge: "\(model.people.filter(\.active).count)") sidebarRow(.team, badge: "\(model.people.filter(\.active).count)")
sidebarRow(.statistics) sidebarRow(.statistics)
sidebarRow(.dispatch)
} header: { } header: {
sidebarHeader("Planung") sidebarHeader("Planung")
} }
@@ -128,6 +128,8 @@ private struct SnapshotContent: View {
screen { ExchangeView() } screen { ExchangeView() }
case "settings": case "settings":
screen { SettingsView() } screen { SettingsView() }
case "dispatch":
screen { DispatchView() }
case "person": case "person":
PersonEditorSheet(request: PersonEditorRequest(person: model.people.first)) PersonEditorSheet(request: PersonEditorRequest(person: model.people.first))
case "detail": case "detail":
@@ -0,0 +1,540 @@
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.
struct DispatchView: View {
@EnvironmentObject private var model: PlanModel
private static let timestampFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "de_DE")
formatter.dateFormat = "dd.MM.yyyy, HH:mm"
return formatter
}()
private var recipients: [DispatchRecipient] { model.dispatchRecipients }
private var emailRecipients: [DispatchRecipient] {
recipients.filter { $0.effectiveChannel == .email }
}
private var printRecipients: [DispatchRecipient] {
recipients.filter { $0.effectiveChannel == .print }
}
var body: some View {
VStack(spacing: 14) {
PageHeader(
eyebrow: "Planung",
title: "Versendung",
subtitle: "Den Plan des aktuellen Zeitraums persönlich per E-Mail oder als Sammel-Ausdruck weitergeben."
) {
HStack(spacing: 8) {
SecondaryActionButton(title: "Einstellungen speichern", icon: "square.and.arrow.down") {
model.saveDispatchSettings()
}
SecondaryActionButton(
title: "Ausdruck-PDF",
icon: "printer",
action: { model.createDispatchPrintPDF() },
disabled: printRecipients.isEmpty
)
PrimaryActionButton(
title: "E-Mails öffnen (\(emailRecipients.count))",
icon: "envelope",
action: { model.openDispatchEmails() },
disabled: emailRecipients.isEmpty
)
}
}
ScrollView {
VStack(alignment: .leading, spacing: 14) {
if model.people.isEmpty {
SurfaceCard {
EmptyStateView(
icon: "person.2.slash",
title: "Noch keine Personen",
message: "Legen Sie zuerst Lektoren und Kommunionhelfer an, um den Plan zu versenden.",
actionTitle: "Zum Team",
action: { model.section = .team }
)
}
} else {
rangeBanner
textsCard
recipientsCard
if !model.dispatchLastBatch.isEmpty {
lastBatchCard
}
if !model.dispatchLog.isEmpty {
historyCard
}
}
}
.padding(.bottom, 16)
}
}
.padding(.horizontal, 22)
.padding(.top, 30)
.padding(.bottom, 18)
}
// MARK: - Range
private var rangeBanner: some View {
SurfaceCard(padding: 13, radius: 14, background: LP.card.opacity(0.9)) {
HStack(spacing: 12) {
Image(systemName: "calendar.badge.clock")
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(LP.accent)
.frame(width: 30, height: 30)
.background(Circle().fill(LP.accent.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text("Planungszeitraum")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
Text(model.range.title)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(LP.ink)
}
Spacer()
HStack(spacing: 14) {
countLabel("\(recipients.count)", "Empfänger")
countLabel("\(emailRecipients.count)", "per E-Mail")
countLabel("\(printRecipients.count)", "als Ausdruck")
}
SecondaryActionButton(title: "Zeitraum ändern", icon: "slider.horizontal.3") {
model.section = .planning
}
}
}
}
private func countLabel(_ value: String, _ label: String) -> some View {
VStack(alignment: .trailing, spacing: 0) {
Text(value)
.font(.system(size: 13, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
Text(label)
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
}
}
// MARK: - Texts
private var textsCard: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
cardHeader(
icon: "text.alignleft",
title: "Anschreiben",
subtitle: "Gilt einheitlich für alle E-Mails und Vorblätter",
tint: LP.accent
)
HStack(alignment: .top, spacing: 14) {
VStack(alignment: .leading, spacing: 5) {
Text("Einleitung")
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(LP.inkTertiary)
TextEditor(text: $model.dispatchIntro)
.font(.system(size: 11.5))
.scrollContentBackground(.hidden)
.padding(8)
.frame(minHeight: 108)
.background(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.fill(LP.cardMuted)
)
.overlay(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.strokeBorder(LP.line.opacity(0.8), lineWidth: 1)
)
}
VStack(alignment: .leading, spacing: 5) {
Text("Abschlussgruß")
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(LP.inkTertiary)
TextEditor(text: $model.dispatchGreeting)
.font(.system(size: 11.5))
.scrollContentBackground(.hidden)
.padding(8)
.frame(minHeight: 108)
.background(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.fill(LP.cardMuted)
)
.overlay(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.strokeBorder(LP.line.opacity(0.8), lineWidth: 1)
)
}
.frame(width: 260)
}
HStack(spacing: 6) {
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.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
}
// MARK: - Recipients
private var recipientsCard: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
HStack(alignment: .top) {
cardHeader(
icon: "paperplane",
title: "Empfänger",
subtitle: "Kanal, Liste und Vorblatt je Person",
tint: LP.burgundy
)
Spacer()
bulkActions
}
HStack(spacing: 8) {
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.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
}
recipientsHeader
Hairline()
ForEach(recipients) { recipient in
recipientRow(recipient)
if recipient.id != recipients.last?.id {
Hairline()
}
}
}
}
}
private var bulkActions: some View {
HStack(spacing: 6) {
bulkButton("Alle E-Mail", icon: "envelope") {
model.setDispatchChannelForAll(.email)
}
bulkButton("Alle Ausdruck", icon: "printer") {
model.setDispatchChannelForAll(.print)
}
bulkButton("Alle kompakt", icon: "list.bullet") {
for recipient in recipients {
model.setDispatchVariant(.compact, for: recipient.person)
}
}
bulkButton("Alle ausführlich", icon: "doc.text") {
for recipient in recipients {
model.setDispatchVariant(.full, for: recipient.person)
}
}
}
}
private func bulkButton(_ title: String, icon: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
HStack(spacing: 4) {
Image(systemName: icon)
.font(.system(size: 9, weight: .semibold))
Text(title)
.font(.system(size: 9.5, weight: .medium))
}
.foregroundStyle(LP.inkSecondary)
.padding(.horizontal, 8)
.padding(.vertical, 5)
.background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(LP.cardMuted))
.overlay(
RoundedRectangle(cornerRadius: 7, style: .continuous)
.strokeBorder(LP.line.opacity(0.7), lineWidth: 0.8)
)
}
.buttonStyle(.plain)
}
private var recipientsHeader: some View {
HStack(spacing: 10) {
Text("PERSON")
.frame(maxWidth: .infinity, alignment: .leading)
Text("E-MAIL-ADRESSE")
.frame(width: 168, alignment: .leading)
Text("KANAL")
.frame(width: 200, alignment: .leading)
Text("LISTE")
.frame(width: 136, alignment: .leading)
Text("VORBLATT")
.frame(width: 66, alignment: .center)
}
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(0.7)
.foregroundStyle(LP.inkTertiary)
.padding(.horizontal, 4)
}
private func recipientRow(_ recipient: DispatchRecipient) -> some View {
HStack(spacing: 10) {
HStack(spacing: 9) {
Avatar(
initials: recipient.person.initials,
color: recipient.person.roles.contains(.lector) ? LP.accent : LP.burgundy,
size: 26
)
VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 6) {
Text(recipient.person.fullName)
.font(.system(size: 11.5, weight: .semibold))
.foregroundStyle(LP.ink)
.lineLimit(1)
if !recipient.assignments.isEmpty {
TinyBadge(
text: "\(recipient.assignments.count)",
color: recipient.effectiveChannel == .email ? LP.accent : LP.burgundy
)
}
}
Text(recipient.person.roleLabel)
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.lineLimit(1)
}
Spacer(minLength: 4)
}
.frame(maxWidth: .infinity, alignment: .leading)
Text(recipient.hasEmail ? recipient.person.email : "keine Adresse")
.font(.system(size: 10))
.foregroundStyle(recipient.hasEmail ? LP.inkSecondary : LP.inkTertiary)
.lineLimit(1)
.truncationMode(.middle)
.frame(width: 168, alignment: .leading)
Picker("", selection: channelBinding(recipient)) {
ForEach(channelOptions(for: recipient)) { channel in
Text(channel.title).tag(channel)
}
}
.labelsHidden()
.pickerStyle(.segmented)
.frame(width: 200)
Picker("", selection: variantBinding(recipient)) {
ForEach(PlanListVariant.allCases) { variant in
Text(variant.title).tag(variant)
}
}
.labelsHidden()
.pickerStyle(.menu)
.frame(width: 136)
Toggle("", isOn: coverBinding(recipient))
.labelsHidden()
.toggleStyle(.checkbox)
.frame(width: 66)
.disabled(recipient.effectiveChannel == .none)
.help("Anschreiben als Vorblatt voranstellen")
}
.padding(.horizontal, 4)
.padding(.vertical, 5)
.opacity(recipient.effectiveChannel == .none ? 0.55 : 1)
}
private func channelOptions(for recipient: DispatchRecipient) -> [DispatchChannel] {
recipient.hasEmail ? [.email, .print, .none] : [.print, .none]
}
private func channelBinding(_ recipient: DispatchRecipient) -> Binding<DispatchChannel> {
Binding(
get: { recipient.preference.channel },
set: { model.setDispatchChannel($0, for: recipient.person) }
)
}
private func variantBinding(_ recipient: DispatchRecipient) -> Binding<PlanListVariant> {
Binding(
get: { recipient.preference.variant },
set: { model.setDispatchVariant($0, for: recipient.person) }
)
}
private func coverBinding(_ recipient: DispatchRecipient) -> Binding<Bool> {
Binding(
get: { recipient.preference.cover },
set: { model.setDispatchCover($0, for: recipient.person) }
)
}
// MARK: - Last batch
private var lastBatchCard: some View {
let batch = model.dispatchLastBatch
let sent = batch.filter { $0.status == .mail }.count
let printed = batch.filter { $0.status == .pdf }.count
let failed = batch.filter { $0.status == .failed }.count
return SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .top) {
cardHeader(
icon: "clock.arrow.circlepath",
title: "Letzte Versendung",
subtitle: batch.first.map {
"\(Self.timestampFormatter.string(from: $0.createdAt)) · \(DayMath.key(batch.first?.rangeStart ?? model.range.start)) – \(DayMath.key(batch.first?.rangeEnd ?? model.range.end))"
} ?? "",
tint: LP.success
)
Spacer()
HStack(spacing: 6) {
if sent > 0 { TinyBadge(text: "\(sent) E-Mail", color: LP.accent) }
if printed > 0 { TinyBadge(text: "\(printed) Ausdruck", color: LP.burgundy) }
if failed > 0 { TinyBadge(text: "\(failed) fehlgeschlagen", color: LP.danger) }
}
}
logList(batch)
}
}
}
// MARK: - History
private var historyCard: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 10) {
cardHeader(
icon: "tray.full",
title: "Versendungsprotokoll",
subtitle: "Was für welchen Zeitraum an wen versendet wurde",
tint: LP.inkSecondary
)
ForEach(historyGroups) { group in
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 8) {
Text(Self.timestampFormatter.string(from: group.createdAt))
.font(.system(size: 10, weight: .semibold))
.foregroundStyle(LP.ink)
Text("\(DayMath.key(group.entries.first?.rangeStart ?? model.range.start)) – \(DayMath.key(group.entries.first?.rangeEnd ?? model.range.end))")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
Spacer()
Text("\(group.entries.count) \(group.entries.count == 1 ? "Empfänger" : "Empfänger")")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
logList(group.entries)
}
.padding(.vertical, 6)
if group.id != historyGroups.last?.id {
Hairline()
}
}
}
}
}
private struct HistoryGroup: Identifiable {
var id: String { batchID }
var batchID: String
var createdAt: Date
var entries: [DispatchLogEntry]
}
private var historyGroups: [HistoryGroup] {
var order: [String] = []
var grouped: [String: [DispatchLogEntry]] = [:]
for entry in model.dispatchLog {
if grouped[entry.batchID] == nil {
order.append(entry.batchID)
}
grouped[entry.batchID, default: []].append(entry)
}
return order.prefix(12).compactMap { batchID in
guard let entries = grouped[batchID], let first = entries.first else { return nil }
return HistoryGroup(batchID: batchID, createdAt: first.createdAt, entries: entries)
}
}
private func logList(_ entries: [DispatchLogEntry]) -> some View {
VStack(spacing: 0) {
ForEach(entries) { entry in
HStack(spacing: 8) {
Image(systemName: entry.channel.symbolName)
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(entry.channel == .email ? LP.accent : LP.burgundy)
.frame(width: 16)
Text(entry.personName)
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
.frame(width: 150, alignment: .leading)
Text(entry.variant.shortTitle)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
.frame(width: 92, alignment: .leading)
if entry.channel == .print {
Text(entry.cover ? "mit Vorblatt" : "ohne Vorblatt")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.frame(width: 96, alignment: .leading)
} else {
Text(entry.email)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.lineLimit(1)
.truncationMode(.middle)
.frame(width: 96, alignment: .leading)
}
Text(entry.status.title)
.font(.system(size: 9))
.foregroundStyle(statusColor(entry.status))
.lineLimit(1)
Spacer(minLength: 0)
}
.padding(.vertical, 3)
}
}
}
private func statusColor(_ status: DispatchStatus) -> Color {
switch status {
case .mail: LP.accent
case .pdf: LP.burgundy
case .failed: LP.danger
}
}
// MARK: - Shared
private func cardHeader(icon: String, title: String, subtitle: String, tint: Color) -> some View {
HStack(spacing: 9) {
Image(systemName: icon)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(tint)
.frame(width: 28, height: 28)
.background(Circle().fill(tint.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text(title)
.font(.system(size: 12.5, weight: .semibold))
.foregroundStyle(LP.ink)
Text(subtitle)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
}
}
}
}
+111 -1
View File
@@ -145,6 +145,31 @@ public final class AppDatabase {
key TEXT PRIMARY KEY, key TEXT PRIMARY KEY,
value TEXT NOT NULL value TEXT NOT NULL
); );
CREATE TABLE IF NOT EXISTS dispatch_preferences (
person_id TEXT PRIMARY KEY,
channel TEXT NOT NULL DEFAULT 'email',
variant TEXT NOT NULL DEFAULT 'compact',
cover INTEGER NOT NULL DEFAULT 1,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS dispatch_log (
id TEXT PRIMARY KEY,
batch_id TEXT NOT NULL,
range_start TEXT NOT NULL,
range_end TEXT NOT NULL,
person_id TEXT NOT NULL DEFAULT '',
person_name TEXT NOT NULL DEFAULT '',
channel TEXT NOT NULL,
variant TEXT NOT NULL DEFAULT '',
cover INTEGER NOT NULL DEFAULT 0,
email TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_dispatch_log_created ON dispatch_log(created_at);
""" """
try database.execute(schema) try database.execute(schema)
// Older databases predate the free-text location for special services. // Older databases predate the free-text location for special services.
@@ -153,7 +178,7 @@ public final class AppDatabase {
column: "location", column: "location",
definition: "TEXT NOT NULL DEFAULT ''" definition: "TEXT NOT NULL DEFAULT ''"
) )
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('schemaVersion', '2')") try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('schemaVersion', '3')")
} }
private func addColumnIfMissing(table: String, column: String, definition: String) throws { private func addColumnIfMissing(table: String, column: String, definition: String) throws {
@@ -658,6 +683,90 @@ public final class AppDatabase {
) )
} }
// MARK: - Dispatch
public func dispatchPreferences() throws -> [String: DispatchPreference] {
try database.query("SELECT * FROM dispatch_preferences").reduce(into: [:]) { result, row in
guard let personID = row.string("person_id") else { return }
result[personID] = DispatchPreference(
channel: DispatchChannel(rawValue: row.string("channel", default: "email")) ?? .email,
variant: PlanListVariant(rawValue: row.string("variant", default: "compact")) ?? .compact,
cover: row.bool("cover", default: true)
)
}
}
public func saveDispatchPreference(_ preference: DispatchPreference, personID: String) {
try? database.run("""
INSERT INTO dispatch_preferences(person_id, channel, variant, cover, updated_at)
VALUES(?, ?, ?, ?, ?)
ON CONFLICT(person_id) DO UPDATE SET
channel=excluded.channel, variant=excluded.variant,
cover=excluded.cover, updated_at=excluded.updated_at
""", [
.text(personID), .text(preference.channel.rawValue),
.text(preference.variant.rawValue), .bool(preference.cover),
.text(ISO8601DateFormatter().string(from: Date()))
])
}
public func dispatchLog(limit: Int = 80) throws -> [DispatchLogEntry] {
let bounded = max(1, min(limit, 500))
return try database.query("""
SELECT * FROM dispatch_log ORDER BY created_at DESC, id DESC LIMIT ?
""", [.int(bounded)]).compactMap { row in
guard let id = row.string("id"),
let batchID = row.string("batch_id"),
let start = row.date("range_start"),
let end = row.date("range_end"),
let channel = DispatchChannel(rawValue: row.string("channel", default: "print")),
let status = DispatchStatus(rawValue: row.string("status", default: "pdf"))
else { return nil }
let created = ISO8601DateFormatter().date(from: row.string("created_at", default: "")) ?? Date()
return DispatchLogEntry(
id: id,
batchID: batchID,
rangeStart: start,
rangeEnd: end,
personID: row.string("person_id", default: ""),
personName: row.string("person_name", default: ""),
channel: channel,
variant: PlanListVariant(rawValue: row.string("variant", default: "compact")) ?? .compact,
cover: row.bool("cover"),
email: row.string("email", default: ""),
status: status,
detail: row.string("detail", default: ""),
createdAt: created
)
}
}
public func appendDispatchLog(_ entries: [DispatchLogEntry]) throws {
guard !entries.isEmpty else { return }
try database.transaction {
let formatter = ISO8601DateFormatter()
for entry in entries {
try database.run("""
INSERT INTO dispatch_log(id, batch_id, range_start, range_end, person_id, person_name,
channel, variant, cover, email, status, detail, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", [
.text(entry.id), .text(entry.batchID),
.dateKey(entry.rangeStart), .dateKey(entry.rangeEnd),
.text(entry.personID), .text(entry.personName),
.text(entry.channel.rawValue), .text(entry.variant.rawValue),
.bool(entry.cover), .text(entry.email),
.text(entry.status.rawValue), .text(entry.detail),
.text(formatter.string(from: entry.createdAt))
])
}
}
}
public func deleteDispatchLog() throws {
try database.run("DELETE FROM dispatch_log")
}
// MARK: - Settings // MARK: - Settings
public func setting(_ key: String) -> String? { public func setting(_ key: String) -> String? {
@@ -768,6 +877,7 @@ public final class AppDatabase {
DELETE FROM assignments; DELETE FROM services; DELETE FROM service_exceptions; DELETE FROM assignments; DELETE FROM services; DELETE FROM service_exceptions;
DELETE FROM service_templates; DELETE FROM absences; DELETE FROM people; DELETE FROM service_templates; DELETE FROM absences; DELETE FROM people;
DELETE FROM churches; DELETE FROM liturgical_days; DELETE FROM churches; DELETE FROM liturgical_days;
DELETE FROM dispatch_preferences; DELETE FROM dispatch_log;
""") """)
if markDemoSuppressed { if markDemoSuppressed {
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('suppressDemoSeed', '1')") try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('suppressDemoSeed', '1')")
+133
View File
@@ -0,0 +1,133 @@
import Foundation
/// How a recipient receives the plan.
public enum DispatchChannel: String, Codable, CaseIterable, Identifiable, Sendable {
case email
case print
case none
public var id: String { rawValue }
public var title: String {
switch self {
case .email: "E-Mail"
case .print: "Ausdruck"
case .none: "Kein Versand"
}
}
public var symbolName: String {
switch self {
case .email: "envelope.fill"
case .print: "printer.fill"
case .none: "minus.circle"
}
}
}
/// Which list is attached to a dispatch.
public enum PlanListVariant: String, Codable, CaseIterable, Identifiable, Sendable {
case compact
case full
public var id: String { rawValue }
public var title: String {
switch self {
case .compact: "Kompaktansicht"
case .full: "Ausführlicher Plan"
}
}
public var shortTitle: String {
switch self {
case .compact: "Kompaktliste"
case .full: "Plan"
}
}
}
/// Stored dispatch preference for one person.
public struct DispatchPreference: Equatable, Sendable {
public var channel: DispatchChannel
public var variant: PlanListVariant
public var cover: Bool
public init(channel: DispatchChannel = .email, variant: PlanListVariant = .compact, cover: Bool = true) {
self.channel = channel
self.variant = variant
self.cover = cover
}
/// A selected e-mail channel without a stored address falls back to print,
/// mirroring the web version.
public func effectiveChannel(for person: Person) -> DispatchChannel {
if channel == .email && person.email.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return .print
}
return channel
}
}
/// Outcome recorded in the dispatch log. The macOS app opens e-mails in the
/// default mail client instead of sending them over SMTP.
public enum DispatchStatus: String, Codable, CaseIterable, Sendable {
case mail
case pdf
case failed
public var title: String {
switch self {
case .mail: "Im Mailprogramm geöffnet"
case .pdf: "Druck-PDF erzeugt"
case .failed: "Fehlgeschlagen"
}
}
}
/// One log line of a dispatch batch.
public struct DispatchLogEntry: Identifiable, Equatable, Sendable {
public var id: String
public var batchID: String
public var rangeStart: Date
public var rangeEnd: Date
public var personID: String
public var personName: String
public var channel: DispatchChannel
public var variant: PlanListVariant
public var cover: Bool
public var email: String
public var status: DispatchStatus
public var detail: String
public var createdAt: Date
public init(
id: String = UUID().uuidString,
batchID: String,
rangeStart: Date,
rangeEnd: Date,
personID: String,
personName: String,
channel: DispatchChannel,
variant: PlanListVariant = .compact,
cover: Bool = false,
email: String = "",
status: DispatchStatus,
detail: String = "",
createdAt: Date = Date()
) {
self.id = id
self.batchID = batchID
self.rangeStart = rangeStart
self.rangeEnd = rangeEnd
self.personID = personID
self.personName = personName
self.channel = channel
self.variant = variant
self.cover = cover
self.email = email
self.status = status
self.detail = detail
self.createdAt = createdAt
}
}
@@ -95,6 +95,47 @@ final class CoreTests: XCTestCase {
XCTAssertNil(try db.service(id: service.id)?.location) XCTAssertNil(try db.service(id: service.id)?.location)
} }
func testDispatchPreferencesAndLogRoundTrip() throws {
let db = try AppDatabase.makeInMemory(seedDemo: true)
let preference = DispatchPreference(channel: .print, variant: .full, cover: false)
db.saveDispatchPreference(preference, personID: "p-maria")
let preferences = try db.dispatchPreferences()
XCTAssertEqual(preferences["p-maria"], preference)
XCTAssertNil(preferences["p-anna"])
let start = DayMath.date(fromKey: "2026-03-01")!
let end = DayMath.date(fromKey: "2026-03-31")!
let entry = DispatchLogEntry(
batchID: "batch-1",
rangeStart: start,
rangeEnd: end,
personID: "p-maria",
personName: "Maria Hoffmann",
channel: .print,
variant: .full,
cover: false,
status: .pdf,
detail: "Ohne Vorblatt"
)
try db.appendDispatchLog([entry])
let log = try db.dispatchLog()
XCTAssertEqual(log.count, 1)
let stored = try XCTUnwrap(log.first)
XCTAssertEqual(stored.batchID, "batch-1")
XCTAssertEqual(stored.personName, "Maria Hoffmann")
XCTAssertEqual(stored.channel, .print)
XCTAssertEqual(stored.variant, .full)
XCTAssertEqual(stored.status, .pdf)
XCTAssertEqual(DayMath.key(stored.rangeStart), "2026-03-01")
XCTAssertEqual(DayMath.key(stored.rangeEnd), "2026-03-31")
try db.deleteAllData()
XCTAssertTrue(try db.dispatchPreferences().isEmpty)
XCTAssertTrue(try db.dispatchLog().isEmpty)
}
func testPlannerRespectsAbsenceAndFillsSlots() throws { func testPlannerRespectsAbsenceAndFillsSlots() throws {
let db = try AppDatabase.makeInMemory(seedDemo: false) let db = try AppDatabase.makeInMemory(seedDemo: false)
let church = Church(id: "c1", name: "Testkirche", shortName: "Test", symbol: .chapel, colorHex: "#000000") let church = Church(id: "c1", name: "Testkirche", shortName: "Test", symbol: .chapel, colorHex: "#000000")
+2
View File
@@ -13,6 +13,8 @@ require (
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/phpdave11/gofpdi v1.0.16 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.50.0 // indirect golang.org/x/sys v0.50.0 // indirect
modernc.org/libc v1.80.1 // indirect modernc.org/libc v1.80.1 // indirect
+5
View File
@@ -12,6 +12,11 @@ github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsRe
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/phpdave11/gofpdi v1.0.16 h1:4qi0x31yujXmS4F6L4ZJKtd1DqG/3H/bpQzEZh2dmhY=
github.com/phpdave11/gofpdi v1.0.16/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
+202
View File
@@ -0,0 +1,202 @@
package pdf
import (
"fmt"
"io"
"strings"
"time"
"lektorenplan/domain"
)
// DispatchAssignment is one entry in a recipient's personal overview.
type DispatchAssignment struct {
Date time.Time
TimeMinutes int
Church string
Title string
Role domain.Role
}
// CoverData describes the personal cover sheet of a dispatch packet.
type CoverData struct {
TenantName string
Diocese string
Range domain.DayRange
Person domain.Person
Intro string
Greeting string
Assignments []DispatchAssignment
GeneratedAt time.Time
}
// AssignmentLines returns the personal assignments as readable lines.
func AssignmentLines(assignments []DispatchAssignment) []string {
lines := make([]string, 0, len(assignments))
for _, assignment := range assignments {
lines = append(lines, fmt.Sprintf("%s · %s · %s · %s (%s)",
domain.ShortWeekdayName(assignment.Date),
domain.MediumString(assignment.Date),
domain.TimeString(assignment.TimeMinutes),
assignment.Church,
assignment.Role.Title()))
}
return lines
}
func coverOptions(data CoverData) Options {
return Options{TenantName: data.TenantName, Diocese: data.Diocese, GeneratedAt: data.GeneratedAt}
}
// Cover writes an A4 portrait cover letter with the personal assignment overview.
func Cover(w io.Writer, data CoverData) error {
pdf := newPDF("P")
tr := translator(pdf)
opts := coverOptions(data)
const (
pageWidth = 210.0
margin = 18.0
contentW = pageWidth - margin*2
)
pdf.AddPage()
// Header ---------------------------------------------------------------
setColor(pdf, colors.accent)
pdf.SetFont("Helvetica", "B", 7)
pdf.SetXY(margin, margin)
pdf.CellFormat(contentW, 4, tr("LEKTORENPLAN · "+strings.ToUpper(opts.tenant())), "", 0, "L", false, 0, "")
setColor(pdf, colors.ink)
pdf.SetFont("Times", "B", 20)
pdf.SetXY(margin, margin+6)
pdf.CellFormat(contentW, 9, tr("Gottesdienstplan"), "", 0, "L", false, 0, "")
setColor(pdf, colors.secondary)
pdf.SetFont("Helvetica", "", 10)
pdf.SetXY(margin, margin+16)
pdf.CellFormat(contentW, 5, tr(data.Range.LongTitle()), "", 0, "L", false, 0, "")
setDraw(pdf, colors.line)
pdf.SetLineWidth(0.3)
pdf.Line(margin, margin+24, pageWidth-margin, margin+24)
// Recipient ------------------------------------------------------------
y := margin + 33
setColor(pdf, colors.tertiary)
pdf.SetFont("Helvetica", "B", 6.5)
pdf.SetXY(margin, y)
pdf.CellFormat(contentW, 3.5, tr("EMPFÄNGER"), "", 0, "L", false, 0, "")
setColor(pdf, colors.ink)
pdf.SetFont("Times", "B", 13)
pdf.SetXY(margin, y+4.5)
pdf.CellFormat(contentW, 6, tr(data.Person.FullName()), "", 0, "L", false, 0, "")
if strings.TrimSpace(data.Person.Email) != "" {
setColor(pdf, colors.secondary)
pdf.SetFont("Helvetica", "", 8)
pdf.SetXY(margin, y+10.5)
pdf.CellFormat(contentW, 4, tr(data.Person.Email), "", 0, "L", false, 0, "")
}
y += 22
setColor(pdf, colors.tertiary)
pdf.SetFont("Helvetica", "", 7)
pdf.SetXY(margin, y)
pdf.CellFormat(contentW, 4, tr("Erstellt am "+domain.MediumString(opts.generated())), "", 0, "R", false, 0, "")
// Letter text ----------------------------------------------------------
y += 10
setColor(pdf, colors.ink)
pdf.SetFont("Times", "", 11.5)
pdf.SetXY(margin, y)
pdf.MultiCell(contentW, 5.6, tr(strings.TrimSpace(data.Intro)), "", "L", false)
y = pdf.GetY() + 8
// Assignment table -----------------------------------------------------
setColor(pdf, colors.ink)
pdf.SetFont("Times", "B", 12.5)
pdf.SetXY(margin, y)
pdf.CellFormat(contentW, 6, tr("Ihre Einsätze im Planungszeitraum"), "", 0, "L", false, 0, "")
y += 9
if len(data.Assignments) == 0 {
setColor(pdf, colors.secondary)
pdf.SetFont("Times", "", 10.5)
pdf.SetXY(margin, y)
pdf.MultiCell(contentW, 5.2, tr("Für Sie sind in diesem Zeitraum keine Einsätze eingetragen."), "", "L", false)
y = pdf.GetY() + 8
} else {
columns := []struct {
Label string
Width float64
}{
{"Tag", 50}, {"Zeit", 20}, {"Ort", 44}, {"Dienst", contentW - 114},
}
setFill(pdf, colors.headerWash)
pdf.Rect(margin, y, contentW, 7.5, "F")
x := margin + 2
setColor(pdf, colors.tertiary)
pdf.SetFont("Helvetica", "B", 6.3)
for _, column := range columns {
pdf.SetXY(x, y+2.2)
pdf.CellFormat(column.Width-2, 3.4, tr(strings.ToUpper(column.Label)), "", 0, "L", false, 0, "")
x += column.Width
}
y += 7.5
setDraw(pdf, colors.line)
pdf.Line(margin, y, pageWidth-margin, y)
for _, assignment := range data.Assignments {
if y > 252 {
pdf.AddPage()
y = margin
}
rowHeight := 8.2
setColor(pdf, colors.ink)
pdf.SetFont("Helvetica", "", 7.6)
x = margin + 2
dayLabel := fmt.Sprintf("%s, %d.%d.%d", domain.ShortWeekdayName(assignment.Date),
domain.DayNumber(assignment.Date), domain.Month(assignment.Date), domain.Year(assignment.Date))
values := []string{
dayLabel,
domain.TimeString(assignment.TimeMinutes),
assignment.Church,
assignment.Role.Title() + " · " + assignment.Title,
}
for index, column := range columns {
pdf.SetXY(x, y+2.1)
pdf.CellFormat(column.Width-2, 3.8, tr(fit(pdf, values[index], column.Width-2)), "", 0, "L", false, 0, "")
x += column.Width
}
y += rowHeight
setDraw(pdf, colors.line)
pdf.SetLineWidth(0.15)
pdf.Line(margin, y, pageWidth-margin, y)
}
y += 8
}
// Greeting -------------------------------------------------------------
if strings.TrimSpace(data.Greeting) != "" {
if y > 245 {
pdf.AddPage()
y = margin
}
setColor(pdf, colors.ink)
pdf.SetFont("Times", "", 11.5)
pdf.SetXY(margin, y)
pdf.MultiCell(contentW, 5.6, tr(strings.TrimSpace(data.Greeting)), "", "L", false)
}
// Footer ---------------------------------------------------------------
setColor(pdf, colors.tertiary)
pdf.SetFont("Helvetica", "", 6.5)
pdf.SetXY(margin, 284)
pdf.CellFormat(contentW, 3.4, tr("LektorenPlan · "+opts.tenant()+" · "+data.Range.ShortTitle()), "", 0, "L", false, 0, "")
if err := pdf.Output(w); err != nil {
return err
}
return pdf.Error()
}
+58
View File
@@ -0,0 +1,58 @@
package pdf
import (
"bytes"
"fmt"
"io"
"github.com/go-pdf/fpdf"
"github.com/go-pdf/fpdf/contrib/gofpdi"
)
// Merge concatenates PDF documents page by page, preserving page sizes and
// orientation. It is used for printable dispatch packets that combine a cover
// sheet with the selected plan variant for every recipient.
func Merge(documents [][]byte) ([]byte, error) {
out := fpdf.New("P", "mm", "A4", "")
out.SetMargins(0, 0, 0)
out.SetAutoPageBreak(false, 0)
for _, raw := range documents {
if len(raw) == 0 {
continue
}
var reader io.ReadSeeker = bytes.NewReader(raw)
importer := gofpdi.NewImporter()
template := importer.ImportPageFromStream(out, &reader, 1, "/MediaBox")
sizes := importer.GetPageSizes()
pages := len(sizes)
if pages == 0 {
return nil, fmt.Errorf("PDF ohne Seiten")
}
for page := 1; page <= pages; page++ {
size, ok := sizes[page]["/MediaBox"]
if !ok {
return nil, fmt.Errorf("PDF-Seite %d ohne MediaBox", page)
}
width, height := size["w"], size["h"]
orientation := "P"
if width > height {
orientation = "L"
}
out.AddPageFormat(orientation, fpdf.SizeType{Wd: width, Ht: height})
if page > 1 {
template = importer.ImportPageFromStream(out, &reader, page, "/MediaBox")
}
importer.UseImportedTemplate(out, template, 0, 0, width, height)
}
}
var buffer bytes.Buffer
if err := out.Output(&buffer); err != nil {
return nil, err
}
if err := out.Error(); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
+30 -1
View File
@@ -250,6 +250,35 @@ CREATE TABLE IF NOT EXISTS tenant_settings (
value TEXT NOT NULL, value TEXT NOT NULL,
PRIMARY KEY (tenant_id, key) PRIMARY KEY (tenant_id, key)
); );
CREATE TABLE IF NOT EXISTS dispatch_preferences (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
person_id TEXT NOT NULL,
channel TEXT NOT NULL DEFAULT 'email',
variant TEXT NOT NULL DEFAULT 'compact',
cover INTEGER NOT NULL DEFAULT 1,
updated_at TEXT NOT NULL,
PRIMARY KEY (tenant_id, person_id)
);
CREATE TABLE IF NOT EXISTS dispatch_log (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
batch_id TEXT NOT NULL,
range_start TEXT NOT NULL,
range_end TEXT NOT NULL,
person_id TEXT NOT NULL DEFAULT '',
person_name TEXT NOT NULL DEFAULT '',
channel TEXT NOT NULL,
variant TEXT NOT NULL DEFAULT '',
cover INTEGER NOT NULL DEFAULT 0,
email TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
created_by TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_dispatch_log_tenant ON dispatch_log(tenant_id, created_at);
` `
func (s *Store) migrate(ctx context.Context) error { func (s *Store) migrate(ctx context.Context) error {
@@ -280,7 +309,7 @@ func (s *Store) migrate(ctx context.Context) error {
} }
} }
if _, err := s.db.ExecContext(ctx, if _, err := s.db.ExecContext(ctx,
"INSERT INTO schema_meta(key, value) VALUES('schemaVersion', '2') "+ "INSERT INTO schema_meta(key, value) VALUES('schemaVersion', '3') "+
"ON CONFLICT(key) DO UPDATE SET value=excluded.value"); err != nil { "ON CONFLICT(key) DO UPDATE SET value=excluded.value"); err != nil {
return fmt.Errorf("record schema version: %w", err) return fmt.Errorf("record schema version: %w", err)
} }
+136
View File
@@ -0,0 +1,136 @@
package store
import (
"context"
"database/sql"
"time"
"lektorenplan/domain"
)
// DispatchPreference stores how one person receives the plan.
type DispatchPreference struct {
Channel string
Variant string
Cover bool
}
// DispatchLogEntry records one dispatch action for one person.
type DispatchLogEntry struct {
ID string
TenantID string
BatchID string
RangeStart time.Time
RangeEnd time.Time
PersonID string
PersonName string
Channel string
Variant string
Cover bool
Email string
Status string
Detail string
CreatedAt time.Time
CreatedBy string
}
// DispatchPreferences loads the saved preferences of a tenant.
func (s *Store) DispatchPreferences(ctx context.Context, tenantID string) (map[string]DispatchPreference, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT person_id, channel, variant, cover
FROM dispatch_preferences WHERE tenant_id=?`, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]DispatchPreference{}
for rows.Next() {
var personID string
var cover int
var preference DispatchPreference
if err := rows.Scan(&personID, &preference.Channel, &preference.Variant, &cover); err != nil {
return nil, err
}
preference.Cover = cover != 0
out[personID] = preference
}
return out, rows.Err()
}
// SaveDispatchPreference stores one person's dispatch preference.
func (s *Store) SaveDispatchPreference(ctx context.Context, tenantID, personID, channel, variant string, cover bool) error {
_, err := s.db.ExecContext(ctx, `
INSERT INTO dispatch_preferences(tenant_id, person_id, channel, variant, cover, updated_at)
VALUES(?, ?, ?, ?, ?, ?)
ON CONFLICT(tenant_id, person_id) DO UPDATE SET
channel=excluded.channel, variant=excluded.variant,
cover=excluded.cover, updated_at=excluded.updated_at`,
tenantID, personID, channel, variant, boolInt(cover), nowText())
return err
}
// DispatchLog returns the most recent dispatch entries of a tenant.
func (s *Store) DispatchLog(ctx context.Context, tenantID string, limit int) ([]DispatchLogEntry, error) {
if limit < 1 {
limit = 1
}
if limit > 500 {
limit = 500
}
rows, err := s.db.QueryContext(ctx, `
SELECT id, tenant_id, batch_id, range_start, range_end, person_id, person_name,
channel, variant, cover, email, status, detail, created_at, created_by
FROM dispatch_log WHERE tenant_id=?
ORDER BY created_at DESC, id DESC LIMIT ?`, tenantID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []DispatchLogEntry
for rows.Next() {
var entry DispatchLogEntry
var rangeStart, rangeEnd, created string
var cover int
if err := rows.Scan(&entry.ID, &entry.TenantID, &entry.BatchID, &rangeStart,
&rangeEnd, &entry.PersonID, &entry.PersonName, &entry.Channel,
&entry.Variant, &cover, &entry.Email, &entry.Status, &entry.Detail,
&created, &entry.CreatedBy); err != nil {
return nil, err
}
entry.RangeStart = domain.MustDate(rangeStart)
entry.RangeEnd = domain.MustDate(rangeEnd)
entry.Cover = cover != 0
entry.CreatedAt = parseTime(created)
out = append(out, entry)
}
return out, rows.Err()
}
// AppendDispatchLog records a batch of dispatch actions.
func (s *Store) AppendDispatchLog(ctx context.Context, entries []DispatchLogEntry) error {
if len(entries) == 0 {
return nil
}
return s.transaction(ctx, func(tx *sql.Tx) error {
for _, entry := range entries {
if entry.ID == "" {
entry.ID = domain.NewID()
}
if entry.CreatedAt.IsZero() {
entry.CreatedAt = time.Now().UTC()
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO dispatch_log(id, tenant_id, batch_id, range_start, range_end,
person_id, person_name, channel, variant, cover, email, status, detail,
created_at, created_by)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
entry.ID, entry.TenantID, entry.BatchID, domain.Key(entry.RangeStart),
domain.Key(entry.RangeEnd), entry.PersonID, entry.PersonName, entry.Channel,
entry.Variant, boolInt(entry.Cover), entry.Email, entry.Status, entry.Detail,
entry.CreatedAt.Format(time.RFC3339), entry.CreatedBy); err != nil {
return err
}
}
return nil
})
}
+2
View File
@@ -99,6 +99,8 @@ func (s *Store) DeleteAllTenantData(ctx context.Context, tenantID string) error
"DELETE FROM absences WHERE tenant_id=?", "DELETE FROM absences WHERE tenant_id=?",
"DELETE FROM people WHERE tenant_id=?", "DELETE FROM people WHERE tenant_id=?",
"DELETE FROM churches WHERE tenant_id=?", "DELETE FROM churches WHERE tenant_id=?",
"DELETE FROM dispatch_preferences WHERE tenant_id=?",
"DELETE FROM dispatch_log WHERE tenant_id=?",
"DELETE FROM tenant_settings WHERE tenant_id=?", "DELETE FROM tenant_settings WHERE tenant_id=?",
} }
for _, statement := range statements { for _, statement := range statements {
+678
View File
@@ -0,0 +1,678 @@
package web
import (
"bytes"
"context"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
"lektorenplan/domain"
"lektorenplan/pdf"
"lektorenplan/store"
)
const (
defaultDispatchIntro = "Liebe Lektorinnen und Lektoren, liebe Kommunionhelferinnen und -helfer,\n\n" +
"anbei sende ich den Plan für den Zeitraum von {start} bis {end}. " +
"Dabei konnten hoffentlich alle Wünsche und Termine berücksichtigt werden."
defaultDispatchGreeting = "Mit freundlichen Grüßen\nIhr Pfarreiteam"
dispatchChannelEmail = "email"
dispatchChannelPrint = "print"
dispatchChannelNone = "none"
dispatchVariantCompact = "compact"
dispatchVariantFull = "full"
dispatchIntroKey = "dispatch.intro"
dispatchGreetingKey = "dispatch.greeting"
)
type dispatchAssignmentView struct {
Date time.Time
DateLabel string
TimeLabel string
Church string
Title string
Role domain.Role
RoleLabel string
SortMinutes int
}
type dispatchPersonView struct {
Person domain.Person
Channel string
Variant string
Cover bool
Effective string
Assignments []dispatchAssignmentView
AssignmentCount int
}
type dispatchPageData struct {
Range domain.DayRange
Start string
End string
PrevStart string
PrevEnd string
NextStart string
NextEnd string
People []dispatchPersonView
Intro string
Greeting string
SMTPConfigured bool
SMTPFrom string
EmailCount int
PrintCount int
NoneCount int
LastEntry *store.DispatchLogEntry
LastBatch []store.DispatchLogEntry
History []store.DispatchLogEntry
OpenSlots int
ServiceCount int
}
type dispatchSelection struct {
Channel string
Variant string
Cover bool
}
type dispatchForm struct {
Range domain.DayRange
Intro string
Greeting string
Selections map[string]dispatchSelection
}
func dispatchDateLabel(t time.Time) string {
return fmt.Sprintf("%d. %s %d", domain.DayNumber(t), domain.MonthName(t), domain.Year(t))
}
func dispatchChannelLabel(channel string) string {
switch channel {
case dispatchChannelEmail:
return "E-Mail"
case dispatchChannelPrint:
return "Ausdruck"
case dispatchChannelNone:
return "Nicht versenden"
default:
return channel
}
}
func dispatchVariantLabel(variant string) string {
if normalizeDispatchVariant(variant) == dispatchVariantFull {
return "Ausführlicher Plan"
}
return "Kompaktansicht"
}
func dispatchStatusLabel(status string) string {
switch status {
case "sent":
return "E-Mail versendet"
case "failed":
return "Fehlgeschlagen"
case "pdf":
return "Druck-PDF erzeugt"
default:
return status
}
}
func resolveDispatchText(value string, rng domain.DayRange) string {
value = strings.ReplaceAll(value, "{start}", dispatchDateLabel(rng.Start))
value = strings.ReplaceAll(value, "{end}", dispatchDateLabel(rng.End))
value = strings.ReplaceAll(value, "{{start}}", dispatchDateLabel(rng.Start))
value = strings.ReplaceAll(value, "{{end}}", dispatchDateLabel(rng.End))
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) {
settings, err := s.store.AllTenantSettings(ctx, tenantID)
if err != nil {
return defaultDispatchIntro, defaultDispatchGreeting
}
intro = defaultDispatchIntro
if value, ok := settings[dispatchIntroKey]; ok && strings.TrimSpace(value) != "" {
intro = value
}
greeting = defaultDispatchGreeting
if value, ok := settings[dispatchGreetingKey]; ok {
greeting = value
}
return intro, greeting
}
func normalizeDispatchChannel(channel, email string) string {
switch strings.ToLower(strings.TrimSpace(channel)) {
case dispatchChannelEmail:
return dispatchChannelEmail
case dispatchChannelPrint:
return dispatchChannelPrint
case dispatchChannelNone:
return dispatchChannelNone
}
if strings.TrimSpace(email) != "" {
return dispatchChannelEmail
}
return dispatchChannelPrint
}
func normalizeDispatchVariant(variant string) string {
if strings.EqualFold(strings.TrimSpace(variant), dispatchVariantFull) {
return dispatchVariantFull
}
return dispatchVariantCompact
}
func effectiveDispatchChannel(channel, email string) string {
if channel == dispatchChannelEmail && strings.TrimSpace(email) == "" {
return dispatchChannelPrint
}
return channel
}
func dispatchAssignments(rows []domain.DayPlanRow, personID string) []dispatchAssignmentView {
var out []dispatchAssignmentView
for _, row := range rows {
for _, service := range row.Services {
for _, assignment := range service.Assignments {
if assignment.PersonID != personID {
continue
}
out = append(out, dispatchAssignmentView{
Date: row.Date, DateLabel: domain.MediumString(row.Date),
TimeLabel: domain.TimeString(service.Service.TimeMinutes),
Church: service.Church.ShortName, Title: service.Service.Title,
Role: assignment.Role, RoleLabel: assignment.Role.Title(),
SortMinutes: service.Service.TimeMinutes,
})
}
}
}
sort.SliceStable(out, func(i, j int) bool {
if !out[i].Date.Equal(out[j].Date) {
return out[i].Date.Before(out[j].Date)
}
return out[i].SortMinutes < out[j].SortMinutes
})
return out
}
func (s *Server) dispatchPeople(ctx context.Context, tenantID string, rows []domain.DayPlanRow) ([]dispatchPersonView, error) {
people, err := s.store.People(ctx, tenantID)
if err != nil {
return nil, err
}
preferences, err := s.store.DispatchPreferences(ctx, tenantID)
if err != nil {
return nil, err
}
var out []dispatchPersonView
for _, person := range people {
if !person.Active {
continue
}
preference := store.DispatchPreference{
Channel: normalizeDispatchChannel("", person.Email),
Variant: dispatchVariantCompact,
Cover: true,
}
if saved, ok := preferences[person.ID]; ok {
preference.Channel = normalizeDispatchChannel(saved.Channel, person.Email)
preference.Variant = normalizeDispatchVariant(saved.Variant)
preference.Cover = saved.Cover
}
// A selected e-mail channel without an address falls back to print.
preference.Channel = effectiveDispatchChannel(preference.Channel, person.Email)
assignments := dispatchAssignments(rows, person.ID)
out = append(out, dispatchPersonView{
Person: person, Channel: preference.Channel, Variant: preference.Variant,
Cover: preference.Cover, Effective: effectiveDispatchChannel(preference.Channel, person.Email),
Assignments: assignments, AssignmentCount: len(assignments),
})
}
return out, nil
}
func (s *Server) handleDispatch(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.renderNoTenant(w, r)
return
}
rng := s.rangeFromRequest(r)
rows, err := s.store.PlanRows(r.Context(), tenant.ID, rng)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error())
return
}
people, err := s.dispatchPeople(r.Context(), tenant.ID, rows)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error())
return
}
history, err := s.store.DispatchLog(r.Context(), tenant.ID, 200)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error())
return
}
config := s.loadSMTPConfig(r.Context(), tenant.ID)
intro, greeting := s.dispatchTexts(r.Context(), tenant.ID)
prev := domain.MonthRange(domain.AddingMonths(-1, rng.Start))
next := domain.MonthRange(domain.AddingMonths(1, rng.Start))
page := dispatchPageData{
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
PrevStart: domain.Key(prev.Start), PrevEnd: domain.Key(prev.End),
NextStart: domain.Key(next.Start), NextEnd: domain.Key(next.End),
People: people, Intro: intro, Greeting: greeting,
SMTPConfigured: config.configured(), SMTPFrom: config.FromAddress,
History: history,
}
for _, person := range people {
switch person.Effective {
case dispatchChannelEmail:
page.EmailCount++
case dispatchChannelPrint:
page.PrintCount++
default:
page.NoneCount++
}
}
for _, row := range rows {
page.ServiceCount += len(row.Services)
for _, service := range row.Services {
page.OpenSlots += service.OpenSlots()
}
}
if len(history) > 0 {
page.LastEntry = &history[0]
for _, entry := range history {
if entry.BatchID != history[0].BatchID {
break
}
page.LastBatch = append(page.LastBatch, entry)
}
if len(history) > 20 {
history = history[:20]
}
page.History = history
}
data := s.baseView(w, r, "Versendung", "dispatch")
data.Data = page
s.renderPage(w, r, "dispatch", data)
}
func (s *Server) dispatchFormFromRequest(r *http.Request, people []domain.Person) dispatchForm {
rng := formRange(r)
form := dispatchForm{
Range: rng, Intro: strings.TrimSpace(r.FormValue("intro")),
Greeting: strings.TrimSpace(r.FormValue("greeting")),
Selections: map[string]dispatchSelection{},
}
if len([]rune(form.Intro)) > 6000 {
form.Intro = string([]rune(form.Intro)[:6000])
}
if len([]rune(form.Greeting)) > 2000 {
form.Greeting = string([]rune(form.Greeting)[:2000])
}
for _, person := range people {
selection := dispatchSelection{
Channel: normalizeDispatchChannel(r.FormValue("channel_"+person.ID), person.Email),
Variant: normalizeDispatchVariant(r.FormValue("variant_" + person.ID)),
Cover: r.FormValue("cover_"+person.ID) == "1",
}
form.Selections[person.ID] = selection
}
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 {
return err
}
if err := s.store.SetTenantSetting(r.Context(), tenantID, dispatchGreetingKey, form.Greeting); err != nil {
return err
}
for personID, selection := range form.Selections {
if err := s.store.SaveDispatchPreference(r.Context(), tenantID, personID,
selection.Channel, selection.Variant, selection.Cover); err != nil {
return err
}
}
return nil
}
func (s *Server) handleDispatchSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.redirect(w, r, "/plan")
return
}
people, err := s.store.People(r.Context(), tenant.ID)
if err != nil {
s.setFlash(w, "Die Empfänger konnten nicht geladen werden: "+err.Error(), "error")
s.redirect(w, r, "/dispatch")
return
}
form := s.dispatchFormFromRequest(r, people)
if err := s.saveDispatchForm(r, tenant.ID, form); err != nil {
s.setFlash(w, "Die Versendung konnte nicht gespeichert werden: "+err.Error(), "error")
} else {
s.setFlash(w, "Versendung gespeichert.", "success")
}
s.redirect(w, r, "/dispatch?start="+domain.Key(form.Range.Start)+"&end="+domain.Key(form.Range.End))
}
func (s *Server) dispatchContextData(ctx context.Context, tenantID string, rng domain.DayRange) ([]domain.DayPlanRow, []domain.Church, []domain.Person, map[string]domain.Person, error) {
rows, err := s.store.PlanRows(ctx, tenantID, rng)
if err != nil {
return nil, nil, nil, nil, err
}
churches, err := s.store.Churches(ctx, tenantID)
if err != nil {
return nil, nil, nil, nil, err
}
people, err := s.store.People(ctx, tenantID)
if err != nil {
return nil, nil, nil, nil, err
}
byID := make(map[string]domain.Person, len(people))
for _, person := range people {
byID[person.ID] = person
}
return rows, churches, people, byID, nil
}
func (s *Server) planPDF(variant string, rng domain.DayRange, rows []domain.DayPlanRow, churches []domain.Church, people []domain.Person, tenant *store.Tenant) ([]byte, error) {
options := pdf.Options{TenantName: tenant.Name, Diocese: s.opts.Diocese, GeneratedAt: domain.Today()}
var buffer bytes.Buffer
if normalizeDispatchVariant(variant) == dispatchVariantCompact {
if err := pdf.CompactPlan(&buffer, rng, rows, people, options); err != nil {
return nil, err
}
} else {
if err := pdf.FullPlan(&buffer, rng, rows, churches, people, options); err != nil {
return nil, err
}
}
return buffer.Bytes(), nil
}
func emailAssignmentTable(assignments []dispatchAssignmentView) string {
if len(assignments) == 0 {
return "Für Sie sind in diesem Zeitraum keine Einsätze eingetragen."
}
var buffer bytes.Buffer
writer := tabwriter.NewWriter(&buffer, 0, 4, 2, ' ', 0)
fmt.Fprintln(writer, "Tag\tZeit\tOrt\tDienst")
fmt.Fprintln(writer, "---\t----\t---\t------")
for _, assignment := range assignments {
fmt.Fprintf(writer, "%s\t%s\t%s\t%s (%s)\n",
assignment.DateLabel, assignment.TimeLabel, assignment.Church,
assignment.Title, assignment.RoleLabel)
}
_ = writer.Flush()
return strings.TrimRight(buffer.String(), "\n")
}
func dispatchEmailBody(intro, greeting string, rng domain.DayRange, assignments []dispatchAssignmentView) string {
parts := []string{resolveDispatchText(intro, rng)}
parts = append(parts, "Ihre Einsätze im Zeitraum:\n\n"+emailAssignmentTable(assignments))
if strings.TrimSpace(greeting) != "" {
parts = append(parts, resolveDispatchText(greeting, rng))
}
return strings.Join(parts, "\n\n")
}
func (s *Server) handleDispatchSend(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.redirect(w, r, "/plan")
return
}
people, err := s.store.People(r.Context(), tenant.ID)
if err != nil {
s.setFlash(w, "Die Empfänger konnten nicht geladen werden: "+err.Error(), "error")
s.redirect(w, r, "/dispatch")
return
}
form := s.dispatchFormFromRequest(r, people)
if err := s.saveDispatchForm(r, tenant.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
}
config := s.loadSMTPConfig(r.Context(), tenant.ID)
if !config.configured() {
s.setFlash(w, "Bitte zuerst die SMTP-Parameter in den Einstellungen hinterlegen.", "error")
s.redirect(w, r, "/dispatch?start="+domain.Key(form.Range.Start)+"&end="+domain.Key(form.Range.End))
return
}
rows, churches, peopleList, _, err := s.dispatchContextData(r.Context(), tenant.ID, form.Range)
if err != nil {
s.setFlash(w, "Der Plan konnte nicht geladen werden: "+err.Error(), "error")
s.redirect(w, r, "/dispatch?start="+domain.Key(form.Range.Start)+"&end="+domain.Key(form.Range.End))
return
}
batchID := domain.NewID()
now := time.Now().UTC()
attachments := map[string][]byte{}
sent, failed, fallback := 0, 0, 0
var firstError string
var entries []store.DispatchLogEntry
for _, person := range peopleList {
if !person.Active {
continue
}
selection, ok := form.Selections[person.ID]
if !ok {
continue
}
channel := effectiveDispatchChannel(selection.Channel, person.Email)
if channel == dispatchChannelNone {
continue
}
if channel != dispatchChannelEmail {
fallback++
continue
}
if _, ok := attachments[selection.Variant]; !ok {
document, err := s.planPDF(selection.Variant, form.Range, rows, churches, peopleList, tenant)
if err != nil {
firstError = err.Error()
failed++
continue
}
attachments[selection.Variant] = document
}
assignments := dispatchAssignments(rows, person.ID)
body := dispatchEmailBody(form.Intro, form.Greeting, form.Range, assignments)
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)
entry := store.DispatchLogEntry{
TenantID: tenant.ID, BatchID: batchID, RangeStart: form.Range.Start,
RangeEnd: form.Range.End, PersonID: person.ID, PersonName: person.FullName(),
Channel: dispatchChannelEmail, Variant: selection.Variant, Cover: false,
Email: person.Email, CreatedAt: now, CreatedBy: user.DisplayName,
}
if err != nil {
failed++
entry.Status = "failed"
entry.Detail = err.Error()
if firstError == "" {
firstError = err.Error()
}
} else {
sent++
entry.Status = "sent"
}
entries = append(entries, entry)
}
if err := s.store.AppendDispatchLog(r.Context(), entries); err != nil {
s.setFlash(w, "Der Versand wurde ausgeführt, das Protokoll konnte aber nicht gespeichert werden: "+err.Error(), "error")
s.redirect(w, r, "/dispatch?start="+domain.Key(form.Range.Start)+"&end="+domain.Key(form.Range.End))
return
}
switch {
case sent == 0 && failed == 0:
s.setFlash(w, "Es wurden keine Empfänger mit E-Mail-Adresse ausgewählt. Nutzen Sie stattdessen die Druck-PDF.", "info")
case failed == 0:
message := fmt.Sprintf("%d E-Mails versendet.", sent)
if fallback > 0 {
message += fmt.Sprintf(" %d Empfänger ohne E-Mail-Adresse wurden für den Ausdruck vorgemerkt.", fallback)
}
s.setFlash(w, message, "success")
default:
message := fmt.Sprintf("%d E-Mails versendet, %d fehlgeschlagen.", sent, failed)
if firstError != "" {
message += " Erster Fehler: " + firstError
}
s.setFlash(w, message, "error")
}
s.redirect(w, r, "/dispatch?start="+domain.Key(form.Range.Start)+"&end="+domain.Key(form.Range.End))
}
func (s *Server) handleDispatchPrint(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.redirect(w, r, "/plan")
return
}
people, err := s.store.People(r.Context(), tenant.ID)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error())
return
}
form := s.dispatchFormFromRequest(r, people)
if err := s.saveDispatchForm(r, tenant.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
}
rows, churches, peopleList, _, err := s.dispatchContextData(r.Context(), tenant.ID, form.Range)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error())
return
}
variantPDFs := map[string][]byte{}
var documents [][]byte
var recipients []dispatchPersonView
now := time.Now().UTC()
batchID := domain.NewID()
for _, person := range peopleList {
if !person.Active {
continue
}
selection, ok := form.Selections[person.ID]
if !ok {
continue
}
if effectiveDispatchChannel(selection.Channel, person.Email) != dispatchChannelPrint {
continue
}
assignments := dispatchAssignments(rows, person.ID)
if selection.Cover {
var cover bytes.Buffer
coverData := pdf.CoverData{
TenantName: tenant.Name, Diocese: s.opts.Diocese, Range: form.Range,
Person: person, Intro: resolveDispatchText(form.Intro, form.Range),
Greeting: resolveDispatchText(form.Greeting, form.Range),
Assignments: make([]pdf.DispatchAssignment, 0, len(assignments)),
GeneratedAt: domain.Today(),
}
for _, assignment := range assignments {
coverData.Assignments = append(coverData.Assignments, pdf.DispatchAssignment{
Date: assignment.Date, TimeMinutes: parseTimeLabel(assignment.TimeLabel),
Church: assignment.Church, Title: assignment.Title, Role: assignment.Role,
})
}
if err := pdf.Cover(&cover, coverData); err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error())
return
}
documents = append(documents, cover.Bytes())
}
variant := normalizeDispatchVariant(selection.Variant)
if _, ok := variantPDFs[variant]; !ok {
document, err := s.planPDF(variant, form.Range, rows, churches, peopleList, tenant)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error())
return
}
variantPDFs[variant] = document
}
documents = append(documents, variantPDFs[variant])
recipients = append(recipients, dispatchPersonView{
Person: person, Channel: dispatchChannelPrint, Variant: variant,
Cover: selection.Cover, Assignments: assignments,
})
}
if len(recipients) == 0 {
s.setFlash(w, "Es sind keine Empfänger für den Ausdruck ausgewählt.", "info")
s.redirect(w, r, "/dispatch?start="+domain.Key(form.Range.Start)+"&end="+domain.Key(form.Range.End))
return
}
packet, err := pdf.Merge(documents)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error())
return
}
entries := make([]store.DispatchLogEntry, 0, len(recipients))
for _, recipient := range recipients {
entries = append(entries, store.DispatchLogEntry{
TenantID: tenant.ID, BatchID: batchID, RangeStart: form.Range.Start,
RangeEnd: form.Range.End, PersonID: recipient.Person.ID,
PersonName: recipient.Person.FullName(), Channel: dispatchChannelPrint,
Variant: recipient.Variant, Cover: recipient.Cover, Email: recipient.Person.Email,
Status: "pdf", Detail: "Druck-PDF erzeugt", CreatedAt: now, CreatedBy: user.DisplayName,
})
}
if err := s.store.AppendDispatchLog(r.Context(), entries); err != nil {
s.setFlash(w, "Das Druck-PDF wurde erzeugt, das Protokoll konnte aber nicht gespeichert werden: "+err.Error(), "error")
}
name := fmt.Sprintf("LektorenPlan-%s-Versand-%s.pdf", tenant.Slug, domain.Key(form.Range.Start))
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
w.Header().Set("Content-Length", strconv.Itoa(len(packet)))
_, _ = w.Write(packet)
}
func parseTimeLabel(label string) int {
parts := strings.Split(strings.TrimSpace(label), ":")
if len(parts) != 2 {
return 0
}
hours, err := strconv.Atoi(parts[0])
if err != nil {
return 0
}
minutes, err := strconv.Atoi(parts[1])
if err != nil {
return 0
}
return hours*60 + minutes
}
func (s *Server) loadSMTPConfig(ctx context.Context, tenantID string) smtpConfig {
port, _ := strconv.Atoi(strings.TrimSpace(s.store.TenantSetting(ctx, tenantID, "smtp.port")))
return smtpConfig{
Host: strings.TrimSpace(s.store.TenantSetting(ctx, tenantID, "smtp.host")),
Port: port,
Username: strings.TrimSpace(s.store.TenantSetting(ctx, tenantID, "smtp.username")),
Password: s.store.TenantSetting(ctx, tenantID, "smtp.password"),
FromAddress: strings.TrimSpace(s.store.TenantSetting(ctx, tenantID, "smtp.fromAddress")),
FromName: strings.TrimSpace(s.store.TenantSetting(ctx, tenantID, "smtp.fromName")),
Encryption: strings.TrimSpace(s.store.TenantSetting(ctx, tenantID, "smtp.encryption")),
}
}
+309
View File
@@ -0,0 +1,309 @@
package web
import (
"context"
"io"
"net/http"
"net/url"
"strings"
"testing"
)
// dispatchRange is a range with seeded demo services and liturgical days.
const dispatchRange = "start=2026-03-01&end=2026-03-31"
func postForm(t *testing.T, client *http.Client, target string, form url.Values) *http.Response {
t.Helper()
resp, err := client.PostForm(target, form)
if err != nil {
t.Fatalf("POST %s: %v", target, err)
}
return resp
}
func TestDispatchPageAndPreferences(t *testing.T) {
ts, st := newTestServer(t)
client := newClient(t)
login(t, client, ts.URL, "editor", "editor123")
body := get(t, client, ts.URL+"/dispatch?"+dispatchRange, http.StatusOK)
if !strings.Contains(body, "Versendung") {
t.Fatal("dispatch page is missing its heading")
}
csrf := extractCSRF(t, body)
ctx := context.Background()
tenants, err := st.Tenants(ctx)
if err != nil || len(tenants) == 0 {
t.Fatalf("tenants: %v", err)
}
tenantID := ""
for _, tenant := range tenants {
people, _ := st.People(ctx, tenant.ID)
for _, person := range people {
if person.ID == "p-markus" {
tenantID = tenant.ID
}
}
}
if tenantID == "" {
t.Fatal("demo tenant with p-markus not found")
}
resp := postForm(t, client, ts.URL+"/dispatch/save", url.Values{
"csrf": {csrf},
"start": {"2026-03-01"},
"end": {"2026-03-31"},
"intro": {"Liebe Leute, anbei der Plan von {start} bis {end}."},
"greeting": {"Mit Grüßen"},
"channel_p-markus": {"print"},
"variant_p-markus": {"full"},
"cover_p-markus": {"1"},
})
resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("save dispatch = %d, want 303", resp.StatusCode)
}
preferences, err := st.DispatchPreferences(ctx, tenantID)
if err != nil {
t.Fatalf("preferences: %v", err)
}
preference, ok := preferences["p-markus"]
if !ok {
t.Fatal("p-markus preference was not stored")
}
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, dispatchGreetingKey); got != "Mit Grüßen" {
t.Fatalf("greeting setting = %q", got)
}
}
func TestDispatchRequiresEditor(t *testing.T) {
ts, _ := newTestServer(t)
reader := newClient(t)
login(t, reader, ts.URL, "reader", "reader123")
get(t, reader, ts.URL+"/dispatch", http.StatusForbidden)
anonymous := newClient(t)
resp, err := anonymous.Get(ts.URL + "/dispatch")
if err != nil {
t.Fatalf("GET /dispatch: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("anonymous /dispatch = %d, want 303", resp.StatusCode)
}
}
func TestDispatchPrintPacketAndLog(t *testing.T) {
ts, st := newTestServer(t)
client := newClient(t)
login(t, client, ts.URL, "editor", "editor123")
body := get(t, client, ts.URL+"/dispatch?"+dispatchRange, http.StatusOK)
csrf := extractCSRF(t, body)
resp := postForm(t, client, ts.URL+"/dispatch/print", url.Values{
"csrf": {csrf},
"start": {"2026-03-01"},
"end": {"2026-03-31"},
"channel_p-maria": {"print"},
"variant_p-maria": {"compact"},
"cover_p-maria": {"1"},
})
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
raw, _ := io.ReadAll(resp.Body)
t.Fatalf("print = %d, want 200\n%s", resp.StatusCode, firstBytes(raw, 300))
}
if contentType := resp.Header.Get("Content-Type"); contentType != "application/pdf" {
t.Fatalf("content type = %q", contentType)
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read PDF: %v", err)
}
if !strings.HasPrefix(string(raw), "%PDF") {
t.Fatalf("response is not a PDF: %q", firstBytes(raw, 20))
}
ctx := context.Background()
tenants, _ := st.Tenants(ctx)
found := false
for _, tenant := range tenants {
entries, err := st.DispatchLog(ctx, tenant.ID, 20)
if err != nil {
t.Fatalf("dispatch log: %v", err)
}
for _, entry := range entries {
if entry.PersonID == "p-maria" && entry.Channel == "print" && entry.Status == "pdf" {
found = true
}
}
}
if !found {
t.Fatal("print dispatch was not logged")
}
}
func TestDispatchSendWithoutSMTPIsRejected(t *testing.T) {
ts, st := newTestServer(t)
client := newClient(t)
login(t, client, ts.URL, "editor", "editor123")
body := get(t, client, ts.URL+"/dispatch?"+dispatchRange, http.StatusOK)
csrf := extractCSRF(t, body)
resp := postForm(t, client, ts.URL+"/dispatch/send", url.Values{
"csrf": {csrf},
"start": {"2026-03-01"},
"end": {"2026-03-31"},
"channel_p-anna": {"email"},
"variant_p-anna": {"compact"},
})
resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("send without SMTP = %d, want 303", resp.StatusCode)
}
if strings.Contains(resp.Header.Get("Location"), "dispatch") == false {
t.Fatalf("redirect = %q, want dispatch page", resp.Header.Get("Location"))
}
// A refused send must not be logged as successful.
ctx := context.Background()
tenants, _ := st.Tenants(ctx)
for _, tenant := range tenants {
entries, _ := st.DispatchLog(ctx, tenant.ID, 10)
for _, entry := range entries {
if entry.Status == "sent" {
t.Fatalf("unexpected sent log entry: %+v", entry)
}
}
}
}
func TestEditorManagesTenantSMTP(t *testing.T) {
ts, st := newTestServer(t)
client := newClient(t)
login(t, client, ts.URL, "editor", "editor123")
body := get(t, client, ts.URL+"/settings", http.StatusOK)
if !strings.Contains(body, "E-Mail-Versand (SMTP)") {
t.Fatal("editor settings do not offer SMTP fields")
}
csrf := extractCSRF(t, body)
resp := postForm(t, client, ts.URL+"/settings/save", url.Values{
"csrf": {csrf},
"smtp_host": {"smtp.example.org"},
"smtp_port": {"587"},
"smtp_username": {"plan"},
"smtp_password": {"secret"},
"smtp_from_address": {"plan@example.org"},
"smtp_from_name": {"Pfarrei"},
"smtp_encryption": {"starttls"},
})
resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("save settings = %d, want 303", resp.StatusCode)
}
ctx := context.Background()
tenants, _ := st.Tenants(ctx)
found := false
for _, tenant := range tenants {
if st.TenantSetting(ctx, tenant.ID, "smtp.host") == "smtp.example.org" {
found = true
if got := st.TenantSetting(ctx, tenant.ID, "smtp.port"); got != "587" {
t.Fatalf("smtp port = %q", got)
}
if got := st.TenantSetting(ctx, tenant.ID, "smtp.password"); got != "secret" {
t.Fatalf("smtp password = %q", got)
}
}
}
if !found {
t.Fatal("SMTP host was not stored as a tenant setting")
}
// The dispatch page now reports a ready SMTP configuration.
page := get(t, client, ts.URL+"/dispatch", http.StatusOK)
if !strings.Contains(page, "SMTP bereit") {
t.Fatal("dispatch page does not reflect the SMTP configuration")
}
// Readers may not change these settings.
reader := newClient(t)
login(t, reader, ts.URL, "reader", "reader123")
readerPage := get(t, reader, ts.URL+"/settings", http.StatusOK)
if strings.Contains(readerPage, "E-Mail-Versand (SMTP)") {
t.Fatal("reader settings must not expose SMTP")
}
}
func TestGuestAccessIsReadOnlyAndAnonymous(t *testing.T) {
ts, st := newTestServer(t)
client := newClient(t)
body := get(t, client, ts.URL+"/guest", http.StatusOK)
if !strings.Contains(body, "Gastzugang") {
t.Fatal("guest page is missing the guest badge")
}
if strings.Contains(body, "/settings") {
t.Fatal("guest page must not link to settings")
}
if !strings.Contains(body, "schott.erzabtei-beuron.de") {
t.Fatal("guest page should link the liturgical readings")
}
if strings.Contains(body, "Anna Berg") || strings.Contains(body, "Markus Weber") {
t.Fatal("guest page must not name assigned people")
}
if !strings.Contains(body, "Lektor") && !strings.Contains(body, "Kommunionhelfer") {
t.Fatal("guest page should still show assignment roles")
}
// Guest data must never contain person records.
ctx := context.Background()
tenants, _ := st.Tenants(ctx)
people, _ := st.People(ctx, tenants[0].ID)
for _, person := range people {
if person.Email != "" && strings.Contains(body, person.Email) {
t.Fatalf("guest page leaks e-mail address %q", person.Email)
}
}
// The guest range picker and tenant switch keep working.
get(t, client, ts.URL+"/guest?"+dispatchRange, http.StatusOK)
get(t, client, ts.URL+"/guest?tid="+url.QueryEscape(tenants[len(tenants)-1].ID), http.StatusOK)
// Write routes stay protected.
loginPage := get(t, client, ts.URL+"/login", http.StatusOK)
if !strings.Contains(loginPage, `href="/guest"`) {
t.Fatal("login page is missing the guest access button")
}
}
func TestGuestHandlerDoesNotExposePeople(t *testing.T) {
ts, _ := newTestServer(t)
resp, err := http.Get(ts.URL + "/guest?start=2025-01-01&end=2025-12-31")
if err != nil {
t.Fatalf("GET /guest: %v", err)
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
body := string(raw)
if !strings.Contains(body, "Liturgie") {
t.Fatal("guest year plan is missing liturgical data")
}
for _, leaked := range []string{"mailto:", "/team", "passwort", "SMTP"} {
if strings.Contains(strings.ToLower(body), strings.ToLower(leaked)) {
t.Fatalf("guest page contains %q", leaked)
}
}
}
+88
View File
@@ -0,0 +1,88 @@
package web
import (
"net/http"
"strings"
"lektorenplan/domain"
"lektorenplan/store"
)
// guestPageData is the read-only public plan. It deliberately contains no
// person records: assignments are shown by role only.
type guestPageData struct {
Range domain.DayRange
Start string
End string
PrevStart string
PrevEnd string
NextStart string
NextEnd string
Rows []domain.DayPlanRow
Churches []domain.Church
Tenants []store.Tenant
TenantID string
TenantName string
ServiceCount int
OpenSlots int
Today string
}
// handleGuest renders the plan without authentication. It never exposes
// settings, write actions or the names of assigned people.
func (s *Server) handleGuest(w http.ResponseWriter, r *http.Request) {
tenants, err := s.store.Tenants(r.Context())
if err != nil {
http.Error(w, "Der Gastzugang ist derzeit nicht verfügbar.", http.StatusInternalServerError)
return
}
if len(tenants) == 0 {
http.Error(w, "Es ist noch keine Pfarrei eingerichtet.", http.StatusNotFound)
return
}
tenant := tenants[0]
if wanted := strings.TrimSpace(r.URL.Query().Get("tid")); wanted != "" {
for i := range tenants {
if tenants[i].ID == wanted || strings.EqualFold(tenants[i].Slug, wanted) {
tenant = tenants[i]
break
}
}
}
rng := s.rangeFromRequest(r)
rows, err := s.store.PlanRows(r.Context(), tenant.ID, rng)
if err != nil {
http.Error(w, "Der Gastzugang ist derzeit nicht verfügbar.", http.StatusInternalServerError)
return
}
churches, err := s.store.Churches(r.Context(), tenant.ID)
if err != nil {
http.Error(w, "Der Gastzugang ist derzeit nicht verfügbar.", http.StatusInternalServerError)
return
}
prev := domain.MonthRange(domain.AddingMonths(-1, rng.Start))
next := domain.MonthRange(domain.AddingMonths(1, rng.Start))
page := guestPageData{
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
PrevStart: domain.Key(prev.Start), PrevEnd: domain.Key(prev.End),
NextStart: domain.Key(next.Start), NextEnd: domain.Key(next.End),
Rows: rows, Churches: churches, Tenants: tenants,
TenantID: tenant.ID, TenantName: tenant.Name,
Today: domain.Key(domain.Today()),
}
for _, row := range rows {
page.ServiceCount += len(row.Services)
page.OpenSlots += row.OpenSlots()
}
data := viewData{
Title: "Gottesdienstplan", Active: "guest", Guest: true,
Version: s.opts.Version, Tenant: &tenant,
LoginQuote: s.loginQuote(r), LoginQuoteSource: s.loginQuoteSource(r),
}
data.Data = page
s.renderPage(w, r, "guest", data)
}
+197
View File
@@ -0,0 +1,197 @@
package web
import (
"bytes"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"fmt"
"mime"
"net"
"net/mail"
"net/smtp"
"strconv"
"strings"
"time"
)
type smtpConfig struct {
Host string
Port int
Username string
Password string
FromAddress string
FromName string
Encryption string
}
func (c smtpConfig) configured() bool {
return strings.TrimSpace(c.Host) != "" && strings.TrimSpace(c.FromAddress) != ""
}
func (c smtpConfig) encryption() string {
switch strings.ToLower(strings.TrimSpace(c.Encryption)) {
case "ssl", "tls":
return "ssl"
case "none", "plain":
return "none"
default:
return "starttls"
}
}
func (c smtpConfig) port() int {
if c.Port > 0 && c.Port <= 65535 {
return c.Port
}
if c.encryption() == "ssl" {
return 465
}
return 587
}
func (c smtpConfig) sender() string {
address := sanitizeHeader(c.FromAddress)
name := sanitizeHeader(c.FromName)
if name == "" {
return address
}
return (&mail.Address{Name: name, Address: address}).String()
}
func sanitizeHeader(value string) string {
value = strings.ReplaceAll(value, "\r", "")
value = strings.ReplaceAll(value, "\n", "")
return strings.TrimSpace(value)
}
func randomBoundary() string {
buffer := make([]byte, 12)
if _, err := rand.Read(buffer); err != nil {
return "lektorenplan-boundary"
}
return "lektorenplan-" + hex.EncodeToString(buffer)
}
func encodeBase64Lines(value []byte) string {
encoded := base64.StdEncoding.EncodeToString(value)
var out strings.Builder
for len(encoded) > 76 {
out.WriteString(encoded[:76])
out.WriteString("\r\n")
encoded = encoded[76:]
}
out.WriteString(encoded)
return out.String()
}
func buildMailMessage(config smtpConfig, to, subject, body string, attachment []byte, attachmentName string) []byte {
boundary := randomBoundary()
var message bytes.Buffer
message.WriteString("From: " + config.sender() + "\r\n")
message.WriteString("To: " + sanitizeHeader(to) + "\r\n")
message.WriteString("Subject: " + mime.QEncoding.Encode("utf-8", sanitizeHeader(subject)) + "\r\n")
message.WriteString("Date: " + time.Now().Format(time.RFC1123Z) + "\r\n")
message.WriteString("MIME-Version: 1.0\r\n")
message.WriteString("Content-Type: multipart/mixed; boundary=\"" + boundary + "\"\r\n")
message.WriteString("\r\n")
message.WriteString("--" + boundary + "\r\n")
message.WriteString("Content-Type: text/plain; charset=utf-8\r\n")
message.WriteString("Content-Transfer-Encoding: base64\r\n\r\n")
message.WriteString(encodeBase64Lines([]byte(body)))
message.WriteString("\r\n")
if len(attachment) > 0 {
name := sanitizeHeader(attachmentName)
if name == "" {
name = "Gottesdienstplan.pdf"
}
message.WriteString("--" + boundary + "\r\n")
message.WriteString("Content-Type: application/pdf; 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("\r\n")
}
message.WriteString("--" + boundary + "--\r\n")
return message.Bytes()
}
func sendMail(config smtpConfig, to, subject, body string, attachment []byte, attachmentName string) error {
if !config.configured() {
return fmt.Errorf("SMTP ist noch nicht konfiguriert")
}
recipient, err := mail.ParseAddress(strings.TrimSpace(to))
if err != nil {
return fmt.Errorf("ungültige E-Mail-Adresse: %w", err)
}
address := net.JoinHostPort(config.Host, strconv.Itoa(config.port()))
tlsConfig := &tls.Config{ServerName: config.Host, MinVersion: tls.VersionTLS12}
dialer := &net.Dialer{Timeout: 20 * time.Second}
var client *smtp.Client
switch config.encryption() {
case "ssl":
connection, err := tls.DialWithDialer(dialer, "tcp", address, tlsConfig)
if err != nil {
return fmt.Errorf("TLS-Verbindung zu %s: %w", address, err)
}
client, err = smtp.NewClient(connection, config.Host)
if err != nil {
connection.Close()
return err
}
case "none":
connection, err := dialer.Dial("tcp", address)
if err != nil {
return fmt.Errorf("Verbindung zu %s: %w", address, err)
}
client, err = smtp.NewClient(connection, config.Host)
if err != nil {
connection.Close()
return err
}
default:
client, err = smtp.Dial(address)
if err != nil {
return fmt.Errorf("Verbindung zu %s: %w", address, err)
}
if ok, _ := client.Extension("STARTTLS"); !ok {
client.Close()
return fmt.Errorf("der Server unterstützt kein STARTTLS")
}
if err := client.StartTLS(tlsConfig); err != nil {
client.Close()
return fmt.Errorf("STARTTLS: %w", err)
}
}
defer client.Close()
if config.Username != "" {
auth := smtp.PlainAuth("", config.Username, config.Password, config.Host)
if err := client.Auth(auth); err != nil {
return fmt.Errorf("SMTP-Anmeldung: %w", err)
}
}
if err := client.Mail(config.FromAddress); err != nil {
return err
}
if err := client.Rcpt(recipient.Address); err != nil {
return err
}
writer, err := client.Data()
if err != nil {
return err
}
if _, err := writer.Write(buildMailMessage(config, recipient.Address, subject, body, attachment, attachmentName)); err != nil {
writer.Close()
return err
}
if err := writer.Close(); err != nil {
return err
}
return client.Quit()
}
+60
View File
@@ -0,0 +1,60 @@
package web
import (
"encoding/base64"
"net/mail"
"strings"
"testing"
)
func TestBuildMailMessageCarriesTextAndPDF(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")
subject := "Gottesdienstplan März 2026 · Pfarrei"
body := "Hallo Anna"
raw := buildMailMessage(config, "anna@example.org", subject, body, attachment, "Plan.pdf")
message, err := mail.ReadMessage(strings.NewReader(string(raw)))
if err != nil {
t.Fatalf("message is not valid mail: %v", err)
}
if got := message.Header.Get("To"); got != "anna@example.org" {
t.Fatalf("To = %q", got)
}
if got := message.Header.Get("MIME-Version"); got != "1.0" {
t.Fatalf("MIME-Version = %q", got)
}
if contentType := message.Header.Get("Content-Type"); !strings.HasPrefix(contentType, "multipart/mixed;") {
t.Fatalf("Content-Type = %q", contentType)
}
text := string(raw)
for _, want := range []string{
"Content-Type: text/plain; charset=utf-8",
"Content-Type: application/pdf",
`filename="Plan.pdf"`,
"Content-Disposition: attachment",
} {
if !strings.Contains(text, want) {
t.Fatalf("message misses %q", want)
}
}
if !strings.Contains(text, base64.StdEncoding.EncodeToString(attachment)) {
t.Fatal("PDF 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")
}
}
func TestSanitizeHeaderStripsLineBreaks(t *testing.T) {
if got := sanitizeHeader("Pfarrei\r\nBcc: evil@example.org"); got != "PfarreiBcc: evil@example.org" {
t.Fatalf("sanitizeHeader = %q", got)
}
}
+6
View File
@@ -27,6 +27,7 @@ type viewData struct {
FlashKind string FlashKind string
IsEditor bool IsEditor bool
IsAdmin bool IsAdmin bool
Guest bool
Version string Version string
DemoMode bool DemoMode bool
LoginQuote string LoginQuote string
@@ -144,6 +145,9 @@ func templateFunctions() template.FuncMap {
"roleTitle": func(role domain.Role) string { return role.Title() }, "roleTitle": func(role domain.Role) string { return role.Title() },
"rolePlural": func(role domain.Role) string { return role.Plural() }, "rolePlural": func(role domain.Role) string { return role.Plural() },
"roleShort": func(role domain.Role) string { return role.ShortCode() }, "roleShort": func(role domain.Role) string { return role.ShortCode() },
"channelLabel": dispatchChannelLabel,
"variantLabel": dispatchVariantLabel,
"statusLabel": dispatchStatusLabel,
"userRole": func(role store.UserRole) string { return store.UserRoleTitle(role) }, "userRole": func(role store.UserRole) string { return store.UserRoleTitle(role) },
"dioceses": func() any { return dioceseOptions }, "dioceses": func() any { return dioceseOptions },
"percent": percentLabel, "percent": percentLabel,
@@ -397,6 +401,8 @@ var iconPaths = map[string]string{
"settings": `<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .34 1.87l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21a2 2 0 1 1-4 0v-.09A1.7 1.7 0 0 0 8.6 19.4a1.7 1.7 0 0 0-1.87.34l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3a2 2 0 1 1 0-4h.09A1.7 1.7 0 0 0 4.6 8.6a1.7 1.7 0 0 0-.34-1.87l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3a2 2 0 1 1 4 0v.09A1.7 1.7 0 0 0 15 4.6a1.7 1.7 0 0 0 1.87-.34l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.7 1.7 0 0 0 19.4 9c.1.4.3.8.6 1 .3.3.7.4 1.1.4H21a2 2 0 1 1 0 4h-.09a1.7 1.7 0 0 0-1.51.6z"/>`, "settings": `<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .34 1.87l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21a2 2 0 1 1-4 0v-.09A1.7 1.7 0 0 0 8.6 19.4a1.7 1.7 0 0 0-1.87.34l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3a2 2 0 1 1 0-4h.09A1.7 1.7 0 0 0 4.6 8.6a1.7 1.7 0 0 0-.34-1.87l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3a2 2 0 1 1 4 0v.09A1.7 1.7 0 0 0 15 4.6a1.7 1.7 0 0 0 1.87-.34l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.7 1.7 0 0 0 19.4 9c.1.4.3.8.6 1 .3.3.7.4 1.1.4H21a2 2 0 1 1 0 4h-.09a1.7 1.7 0 0 0-1.51.6z"/>`,
"shield": `<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/>`, "shield": `<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/>`,
"printer": `<path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>`, "printer": `<path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>`,
"send": `<path d="M22 2L11 13M22 2l-7 20-4-9-9-4z"/>`,
"mail": `<rect x="2" y="4" width="20" height="16" rx="2"/><path d="M3 6l9 7 9-7"/>`,
"plus": `<path d="M12 5v14M5 12h14"/>`, "plus": `<path d="M12 5v14M5 12h14"/>`,
"left": `<path d="M15 18l-6-6 6-6"/>`, "left": `<path d="M15 18l-6-6 6-6"/>`,
"right": `<path d="M9 18l6-6-6-6"/>`, "right": `<path d="M9 18l6-6-6-6"/>`,
+7 -1
View File
@@ -62,7 +62,7 @@ func New(st *store.Store, opts Options) (*Server, error) {
funcs := templateFunctions() funcs := templateFunctions()
names := []string{ names := []string{
"login", "plan", "service", "services", "team", "person", "statistics", "login", "plan", "service", "services", "team", "person", "statistics",
"exchange", "settings", "liturgy", "admin_tenants", "admin_users", "exchange", "settings", "liturgy", "dispatch", "guest", "admin_tenants", "admin_users",
"admin_churches", "password", "error", "no_tenant", "admin_churches", "password", "error", "no_tenant",
} }
views := make(map[string]*template.Template, len(names)) views := make(map[string]*template.Template, len(names))
@@ -122,6 +122,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /login", s.handleLoginGet) mux.HandleFunc("GET /login", s.handleLoginGet)
mux.HandleFunc("POST /login", s.handleLoginPost) mux.HandleFunc("POST /login", s.handleLoginPost)
mux.HandleFunc("GET /guest", s.handleGuest)
mux.HandleFunc("POST /logout", s.auth(s.handleLogout)) mux.HandleFunc("POST /logout", s.auth(s.handleLogout))
mux.HandleFunc("GET /password", s.auth(s.handlePasswordGet)) mux.HandleFunc("GET /password", s.auth(s.handlePasswordGet))
mux.HandleFunc("POST /password", s.auth(s.handlePasswordChange)) mux.HandleFunc("POST /password", s.auth(s.handlePasswordChange))
@@ -164,6 +165,11 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("POST /liturgy/sync", s.editor(s.handleLiturgySync)) mux.HandleFunc("POST /liturgy/sync", s.editor(s.handleLiturgySync))
mux.HandleFunc("GET /pdf", s.auth(s.handlePDF)) mux.HandleFunc("GET /pdf", s.auth(s.handlePDF))
mux.HandleFunc("GET /dispatch", s.editor(s.handleDispatch))
mux.HandleFunc("POST /dispatch/save", s.editor(s.handleDispatchSave))
mux.HandleFunc("POST /dispatch/send", s.editor(s.handleDispatchSend))
mux.HandleFunc("POST /dispatch/print", s.editor(s.handleDispatchPrint))
mux.HandleFunc("GET /admin", s.admin(s.handleAdminRoot)) mux.HandleFunc("GET /admin", s.admin(s.handleAdminRoot))
mux.HandleFunc("GET /admin/tenants", s.admin(s.handleAdminTenants)) mux.HandleFunc("GET /admin/tenants", s.admin(s.handleAdminTenants))
mux.HandleFunc("POST /admin/tenants/save", s.admin(s.handleAdminTenantSave)) mux.HandleFunc("POST /admin/tenants/save", s.admin(s.handleAdminTenantSave))
+63
View File
@@ -21,6 +21,14 @@ type settingsPageData struct {
DemoReset bool DemoReset bool
LoginQuote string LoginQuote string
LoginQuoteSource string LoginQuoteSource string
SMTPHost string
SMTPPort string
SMTPUsername string
SMTPPasswordSet bool
SMTPFromAddress string
SMTPFromName string
SMTPEncryption string
SMTPConfigured bool
} }
const ( const (
@@ -101,6 +109,19 @@ func (s *Server) handleSettings(w http.ResponseWriter, r *http.Request, user *st
LoginQuote: s.loginQuote(r), LoginQuote: s.loginQuote(r),
LoginQuoteSource: s.loginQuoteSource(r), LoginQuoteSource: s.loginQuoteSource(r),
} }
if page.CanEdit {
config := s.loadSMTPConfig(r.Context(), tenant.ID)
page.SMTPHost = config.Host
if config.Port > 0 {
page.SMTPPort = fmt.Sprintf("%d", config.Port)
}
page.SMTPUsername = config.Username
page.SMTPPasswordSet = config.Password != ""
page.SMTPFromAddress = config.FromAddress
page.SMTPFromName = config.FromName
page.SMTPEncryption = config.encryption()
page.SMTPConfigured = config.configured()
}
if page.Diocese == "" { if page.Diocese == "" {
page.Diocese = "koeln" page.Diocese = "koeln"
} }
@@ -141,6 +162,37 @@ func (s *Server) handleSettingsSave(w http.ResponseWriter, r *http.Request, user
} }
} }
// SMTP settings for dispatch e-mails are administered per tenant by the
// editors. The password is only replaced when a new value is entered so
// it never has to be echoed back.
if s.store.CanEditTenant(r.Context(), user, tenant.ID) {
smtpValues := map[string]string{
"smtp.host": strings.TrimSpace(r.FormValue("smtp_host")),
"smtp.username": strings.TrimSpace(r.FormValue("smtp_username")),
"smtp.fromAddress": strings.TrimSpace(r.FormValue("smtp_from_address")),
"smtp.fromName": strings.TrimSpace(r.FormValue("smtp_from_name")),
"smtp.encryption": smtpEncryptionSetting(r.FormValue("smtp_encryption")),
}
if port := parseInt(r.FormValue("smtp_port"), 0); port > 0 && port <= 65535 {
smtpValues["smtp.port"] = fmt.Sprintf("%d", port)
} else {
smtpValues["smtp.port"] = ""
}
for key, value := range smtpValues {
if err := s.store.SetTenantSetting(r.Context(), tenant.ID, key, value); err != nil {
s.setFlash(w, "Die SMTP-Einstellungen konnten nicht gespeichert werden: "+err.Error(), "error")
s.redirect(w, r, "/settings")
return
}
}
switch {
case r.FormValue("smtp_clear_password") == "1":
_ = s.store.SetTenantSetting(r.Context(), tenant.ID, "smtp.password", "")
case strings.TrimSpace(r.FormValue("smtp_password")) != "":
_ = s.store.SetTenantSetting(r.Context(), tenant.ID, "smtp.password", r.FormValue("smtp_password"))
}
}
tenantValues := map[string]string{ tenantValues := map[string]string{
"planner.replaceExisting": boolSetting(r.FormValue("replace_existing")), "planner.replaceExisting": boolSetting(r.FormValue("replace_existing")),
"planner.respectPreferredWeekdays": boolSetting(r.FormValue("respect_weekdays")), "planner.respectPreferredWeekdays": boolSetting(r.FormValue("respect_weekdays")),
@@ -205,6 +257,17 @@ func (s *Server) handleDeleteTenantData(w http.ResponseWriter, r *http.Request,
s.redirect(w, r, "/settings") s.redirect(w, r, "/settings")
} }
func smtpEncryptionSetting(value string) string {
switch strings.ToLower(strings.TrimSpace(value)) {
case "ssl":
return "ssl"
case "none":
return "none"
default:
return "starttls"
}
}
func boolSetting(value string) string { func boolSetting(value string) string {
if value == "1" || value == "on" || value == "true" { if value == "1" || value == "on" || value == "true" {
return "1" return "1"
+25
View File
@@ -173,6 +173,30 @@
}); });
} }
/* Versandweg für alle Empfänger setzen -------------------------------- */
function initDispatchBulk() {
var form = document.querySelector("[data-dispatch-form]");
if (!form) return;
var selects = Array.prototype.slice.call(form.querySelectorAll("[data-dispatch-channel]"));
if (!selects.length) return;
form.querySelectorAll("[data-dispatch-all]").forEach(function (button) {
button.addEventListener("click", function () {
var mode = button.getAttribute("data-dispatch-all");
selects.forEach(function (select) {
if (mode === "reset") {
select.selectedIndex = 0;
return;
}
var option = select.querySelector('option[value="' + mode + '"]');
if (!option && mode === "email") {
option = select.querySelector('option[value="print"]');
}
if (option) option.selected = true;
});
});
});
}
/* Formular-Doppelversand verhindern ------------------------------------ */ /* Formular-Doppelversand verhindern ------------------------------------ */
function initSubmitGuards() { function initSubmitGuards() {
document.querySelectorAll("form").forEach(function (form) { document.querySelectorAll("form").forEach(function (form) {
@@ -195,6 +219,7 @@
initPersonSearch(); initPersonSearch();
initFileDrop(); initFileDrop();
initRangeOutputs(); initRangeOutputs();
initDispatchBulk();
initSubmitGuards(); initSubmitGuards();
}); });
})(); })();
+62
View File
@@ -812,6 +812,65 @@ hr { border: 0; border-top: 1px solid var(--line); margin: 1rem 0; }
.error-page h2 { margin-bottom: .35rem; } .error-page h2 { margin-bottom: .35rem; }
.error-page p { color: var(--muted); font-size: .9rem; margin-bottom: 1rem; } .error-page p { color: var(--muted); font-size: .9rem; margin-bottom: 1rem; }
/* ---------- Versendung ---------- */
.dispatch-page .range-label { font-family: var(--serif); font-size: .95rem; color: var(--ink-soft); }
.dispatch-bulk { display: flex; gap: .3rem; flex-wrap: wrap; justify-content: flex-end; }
.dispatch-table td { vertical-align: top; }
.dispatch-table select { min-width: 9.5rem; }
.dispatch-person { display: flex; flex-direction: column; gap: .1rem; min-width: 11rem; }
.dispatch-person strong { font-size: .9rem; }
.dispatch-person small { color: var(--muted); }
.dispatch-person a { font-size: .78rem; color: var(--green); word-break: break-all; }
.dispatch-no-mail { font-size: .78rem; color: var(--burgundy); }
.dispatch-warn { display: block; color: var(--burgundy); font-size: .72rem; }
.dispatch-cover { white-space: nowrap; }
.dispatch-cover .check { font-size: .8rem; }
.dispatch-details summary { cursor: pointer; color: var(--green-dark); font-size: .8rem; }
.dispatch-details ul { list-style: none; margin: .4rem 0 0; padding: 0; display: flex; flex-direction: column; gap: .2rem; }
.dispatch-details li {
display: grid; grid-template-columns: 6.5rem 3.2rem minmax(4rem, 1fr) auto; gap: .45rem;
font-size: .74rem; color: var(--muted); padding: .18rem .4rem;
border-left: 2px solid var(--line-soft); background: var(--card-alt); border-radius: 0 5px 5px 0;
}
.dispatch-actions { gap: .5rem; flex-wrap: wrap; }
.dispatch-last-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1rem; margin-bottom: .9rem; }
.dispatch-last-grid div { display: flex; flex-direction: column; gap: .1rem; }
.dispatch-last-grid strong { font-family: var(--serif); font-size: 1rem; }
.dispatch-log-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; }
.dispatch-log-list li {
display: flex; flex-wrap: wrap; align-items: baseline; gap: .55rem;
padding: .45rem .2rem; border-bottom: 1px solid var(--line-soft); font-size: .82rem;
}
.dispatch-log-list li:last-child { border-bottom: 0; }
.dispatch-log-list li strong { min-width: 11rem; }
.dispatch-log-list li small { flex-basis: 100%; color: var(--muted); }
.dispatch-log-status { font-size: .72rem; font-weight: 700; letter-spacing: .02em; color: var(--muted); }
.dispatch-log-status.status-sent, .dispatch-log-status.status-pdf { color: var(--green-dark); }
.dispatch-log-status.status-failed { color: var(--burgundy); }
.notice-gold { border-style: dashed; }
/* ---------- Gastzugang ---------- */
.auth-guest {
display: flex; flex-direction: column; gap: .45rem;
margin-top: .9rem; padding-top: .9rem; border-top: 1px dashed var(--line);
}
.auth-guest-note { color: var(--muted); font-size: .76rem; line-height: 1.45; }
.guest-page { background: linear-gradient(180deg, #fbf7ed 0%, var(--paper) 46%, #f1e9d9 100%); }
.guest-shell { min-height: 100vh; display: flex; flex-direction: column; }
.guest-bar {
display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap;
padding: .85rem clamp(1rem, 3vw, 2.2rem);
background: rgba(255, 253, 247, .92); border-bottom: 1px solid var(--line);
backdrop-filter: blur(6px);
}
.guest-bar .brand { display: flex; align-items: center; gap: .7rem; color: var(--ink); }
.guest-actions { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; }
.guest-content { width: 100%; max-width: 1380px; margin: 0 auto; flex: 1; }
.guest-foot { display: flex; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
.guest-service { cursor: default; }
.guest-service:hover { transform: none; }
.stat-strip.three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
/* ---------- Utilities and responsive ---------- */ /* ---------- Utilities and responsive ---------- */
[data-plan-row].filtered { display: none; } [data-plan-row].filtered { display: none; }
[data-plan-row].filtered + [data-plan-row].filtered { border-top: 0; } [data-plan-row].filtered + [data-plan-row].filtered { border-top: 0; }
@@ -882,6 +941,9 @@ hr { border: 0; border-top: 1px solid var(--line); margin: 1rem 0; }
.demo-account-grid { grid-template-columns: 1fr; } .demo-account-grid { grid-template-columns: 1fr; }
.church-overview { grid-template-columns: 1fr; } .church-overview { grid-template-columns: 1fr; }
.topbar-actions .btn span { display: none; } .topbar-actions .btn span { display: none; }
.dispatch-last-grid { grid-template-columns: 1fr; }
.dispatch-actions .btn { width: 100%; justify-content: center; }
.dispatch-bulk { justify-content: flex-start; }
} }
@media print { @media print {
+215
View File
@@ -0,0 +1,215 @@
{{define "content"}}
<div class="page-stack dispatch-page">
<section class="page-intro">
<div>
<span class="eyebrow">Planung · Versendung</span>
<h2>Den Plan an alle Empfänger bringen</h2>
<p>Legen Sie je Person fest, ob der Plan per E-Mail oder als Ausdruck verschickt wird und welche Liste beiliegt. Der E-Mail-Text wird für jede Person mit einer kleinen Übersicht der eigenen Einsätze ergänzt.</p>
</div>
<div class="intro-actions">
{{if .Data.SMTPConfigured}}
<span class="badge badge-green">{{icon "mail"}} SMTP bereit · {{.Data.SMTPFrom}}</span>
{{else}}
<span class="badge badge-gold">{{icon "mail"}} SMTP nicht konfiguriert</span>
{{end}}
</div>
</section>
<section class="toolbar card">
<div class="toolbar-group range-nav">
<a class="icon-button" href="/dispatch?start={{.Data.PrevStart}}&amp;end={{.Data.PrevEnd}}" title="Vorheriger Monat">{{icon "left"}}</a>
<form class="range-form" method="get" action="/dispatch">
<label class="field field-inline"><span>Von</span><input type="date" name="start" value="{{.Data.Start}}"></label>
<label class="field field-inline"><span>Bis</span><input type="date" name="end" value="{{.Data.End}}"></label>
<button class="btn btn-secondary btn-small" type="submit">Anzeigen</button>
</form>
<a class="icon-button" href="/dispatch?start={{.Data.NextStart}}&amp;end={{.Data.NextEnd}}" title="Nächster Monat">{{icon "right"}}</a>
</div>
<div class="toolbar-group">
<span class="range-label">{{rangeLong .Data.Range}}</span>
<a class="chip" href="/dispatch">{{icon "calendar"}} Dieser Monat</a>
</div>
</section>
<section class="stat-strip four">
<article class="mini-stat"><span class="mini-stat-label">E-Mail</span><strong>{{.Data.EmailCount}}</strong><small>Empfänger mit Adresse</small></article>
<article class="mini-stat"><span class="mini-stat-label">Ausdruck</span><strong>{{.Data.PrintCount}}</strong><small>im Sammel-PDF</small></article>
<article class="mini-stat"><span class="mini-stat-label">Ohne Versand</span><strong>{{.Data.NoneCount}}</strong><small>bewusst ausgelassen</small></article>
<article class="mini-stat"><span class="mini-stat-label">Offene Dienste</span><strong>{{.Data.OpenSlots}}</strong><small>in {{.Data.ServiceCount}} Gottesdiensten</small></article>
</section>
{{if not .Data.SMTPConfigured}}
<div class="notice notice-gold">
<span class="notice-mark">{{icon "mail"}}</span>
<div>
<strong>E-Mail-Versand noch nicht eingerichtet</strong>
<p>Hinterlegen Sie die SMTP-Zugangsdaten in den Einstellungen, damit E-Mails direkt verschickt werden können. Ausdrucke funktionieren bereits ohne SMTP.</p>
</div>
<a class="btn btn-secondary btn-small" href="/settings">{{icon "settings"}} Zu den Einstellungen</a>
</div>
{{end}}
<form method="post" action="/dispatch/save" class="page-stack" data-dispatch-form>
<input type="hidden" name="csrf" value="{{.CSRF}}">
<input type="hidden" name="start" value="{{.Data.Start}}">
<input type="hidden" name="end" value="{{.Data.End}}">
<section class="card">
<div class="card-head">
<div><span class="eyebrow">Texte</span><h3>Anschreiben</h3></div>
<span class="count-pill">Platzhalter {start} und {end}</span>
</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.</p>
</div>
<div class="settings-fields">
<label class="field"><span class="field-label">Einleitungstext</span>
<textarea name="intro" rows="6" maxlength="6000">{{.Data.Intro}}</textarea>
</label>
<label class="field"><span class="field-label">Abschlussgrußformel</span>
<textarea name="greeting" rows="3" maxlength="2000">{{.Data.Greeting}}</textarea>
</label>
</div>
</div>
</section>
<section class="card">
<div class="card-head">
<div><span class="eyebrow">Empfänger</span><h3>Versandweg je Person</h3></div>
<div class="dispatch-bulk">
<button class="btn btn-ghost btn-small" type="button" data-dispatch-all="email">Alle E-Mail</button>
<button class="btn btn-ghost btn-small" type="button" data-dispatch-all="print">Alle Ausdruck</button>
<button class="btn btn-ghost btn-small" type="button" data-dispatch-all="reset">Zurücksetzen</button>
</div>
</div>
<div class="table-scroll">
<table class="data-table dispatch-table">
<thead>
<tr>
<th>Person</th>
<th>Einsätze</th>
<th>Versandweg</th>
<th>Liste</th>
<th>Vorblatt</th>
</tr>
</thead>
<tbody>
{{range .Data.People}}
{{$person := .Person}}
{{$effective := .Effective}}
<tr>
<td>
<div class="dispatch-person">
<strong>{{$person.FullName}}</strong>
<small>{{$person.RoleLabel}}</small>
{{if $person.Email}}
<a href="mailto:{{$person.Email}}">{{$person.Email}}</a>
{{else}}
<span class="dispatch-no-mail">keine E-Mail-Adresse hinterlegt</span>
{{end}}
</div>
</td>
<td>
{{if .Assignments}}
<details class="dispatch-details">
<summary>{{.AssignmentCount}} {{if eq .AssignmentCount 1}}Einsatz{{else}}Einsätze{{end}}</summary>
<ul>
{{range .Assignments}}
<li><span>{{.DateLabel}}</span><span>{{.TimeLabel}}</span><span>{{.Church}}</span><span>{{.RoleLabel}}</span></li>
{{end}}
</ul>
</details>
{{else}}
<span class="muted">keine Einsätze</span>
{{end}}
</td>
<td>
<select name="channel_{{$person.ID}}" data-dispatch-channel aria-label="Versandweg für {{$person.FullName}}">
{{if $person.Email}}<option value="email" {{if eq .Channel "email"}}selected{{end}}>E-Mail</option>{{end}}
<option value="print" {{if eq .Channel "print"}}selected{{end}}>Ausdruck</option>
<option value="none" {{if eq .Channel "none"}}selected{{end}}>Nicht versenden</option>
</select>
{{if and (eq .Channel "email") (not $person.Email)}}<small class="dispatch-warn">ohne Adresse → Ausdruck</small>{{end}}
</td>
<td>
<select name="variant_{{$person.ID}}" aria-label="Liste für {{$person.FullName}}">
<option value="compact" {{if eq .Variant "compact"}}selected{{end}}>Kompaktansicht</option>
<option value="full" {{if eq .Variant "full"}}selected{{end}}>Ausführlicher Plan</option>
</select>
</td>
<td class="dispatch-cover">
<label class="check">
<input type="checkbox" name="cover_{{$person.ID}}" value="1" {{if .Cover}}checked{{end}}>
<span>{{if eq $effective "email"}}E-Mail-Text{{else}}Anschreiben{{end}}</span>
</label>
</td>
</tr>
{{else}}
<tr><td colspan="5"><p class="empty-note">Im aktiven Mandanten sind noch keine aktiven Personen hinterlegt.</p></td></tr>
{{end}}
</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.</p>
<div class="card-foot dispatch-actions">
<button class="btn btn-secondary" type="submit">{{icon "check"}} Auswahl speichern</button>
<button class="btn btn-primary" type="submit" formaction="/dispatch/send" data-confirm="Die E-Mails jetzt an alle ausgewählten Empfänger senden?">{{icon "send"}} E-Mails senden</button>
<button class="btn btn-secondary" type="submit" formaction="/dispatch/print" formtarget="_blank">{{icon "printer"}} Druck-PDF erzeugen</button>
</div>
</section>
</form>
{{with .Data.LastEntry}}
<section class="card dispatch-last">
<div class="card-head">
<div><span class="eyebrow">Letzte Versendung</span><h3>{{rangeShort $.Data.Range}} · {{.CreatedAt.Format "02.01.2006, 15:04"}} Uhr</h3></div>
<span class="count-pill">{{len $.Data.LastBatch}} {{if eq (len $.Data.LastBatch) 1}}Eintrag{{else}}Einträge{{end}}</span>
</div>
<div class="dispatch-last-grid">
<div><span class="field-caption">Zeitraum</span><strong>{{shortDate .RangeStart}} – {{shortDate .RangeEnd}}</strong></div>
<div><span class="field-caption">Ausgelöst von</span><strong>{{if .CreatedBy}}{{.CreatedBy}}{{else}}unbekannt{{end}}</strong></div>
<div><span class="field-caption">Aktion</span><strong>{{statusLabel .Status}}</strong></div>
</div>
<ul class="dispatch-log-list">
{{range $.Data.LastBatch}}
<li>
<strong>{{.PersonName}}</strong>
<span>{{channelLabel .Channel}} · {{variantLabel .Variant}}{{if .Cover}} · mit Vorblatt{{end}}</span>
<span class="dispatch-log-status status-{{.Status}}">{{statusLabel .Status}}</span>
{{if .Detail}}<small>{{.Detail}}</small>{{end}}
</li>
{{end}}
</ul>
</section>
{{end}}
{{if .Data.History}}
<section class="card">
<div class="card-head"><div><span class="eyebrow">Protokoll</span><h3>Versendungen im Überblick</h3></div><span class="count-pill">{{len .Data.History}}</span></div>
<div class="table-scroll">
<table class="data-table compact-table">
<thead>
<tr><th>Zeitpunkt</th><th>Zeitraum</th><th>Person</th><th>Kanal</th><th>Liste</th><th>Status</th><th>Von</th></tr>
</thead>
<tbody>
{{range .Data.History}}
<tr>
<td>{{.CreatedAt.Format "02.01.2006, 15:04"}}</td>
<td>{{shortDate .RangeStart}} – {{shortDate .RangeEnd}}</td>
<td>{{.PersonName}}{{if .Email}}<br><small>{{.Email}}</small>{{end}}</td>
<td>{{channelLabel .Channel}}{{if .Cover}}<br><small>mit Vorblatt</small>{{end}}</td>
<td>{{variantLabel .Variant}}</td>
<td><span class="dispatch-log-status status-{{.Status}}">{{statusLabel .Status}}</span></td>
<td>{{.CreatedBy}}</td>
</tr>
{{end}}
</tbody>
</table>
</div>
</section>
{{end}}
</div>
{{end}}
+220
View File
@@ -0,0 +1,220 @@
{{define "content"}}
<div class="page-stack guest-stack">
<section class="page-intro">
<div>
<span class="eyebrow">Öffentlicher Plan · {{.Data.TenantName}}</span>
<h2>{{rangeLong .Data.Range}}</h2>
<p>Alle Gottesdienste mit liturgischen Angaben und Lesungsverweisen – ohne Namen der eingesetzten Personen, ohne Einstellungen und ohne Schreibzugriffe.</p>
</div>
<div class="intro-actions">
{{if gt (len .Data.Tenants) 1}}
<form class="tenant-form" method="get" action="/guest">
<label class="field field-inline"><span>Pfarrei</span>
<select name="tid" onchange="this.form.submit()" aria-label="Pfarrei wählen">
{{range .Data.Tenants}}<option value="{{.ID}}" {{if eq .ID $.Data.TenantID}}selected{{end}}>{{.Name}}</option>{{end}}
</select>
</label>
<noscript><button class="btn btn-secondary btn-small" type="submit">Anzeigen</button></noscript>
</form>
{{end}}
<span class="badge badge-green">Nur Lesen</span>
</div>
</section>
<section class="toolbar card">
<div class="toolbar-group range-nav">
<a class="icon-button" href="/guest?tid={{.Data.TenantID}}&amp;start={{.Data.PrevStart}}&amp;end={{.Data.PrevEnd}}" title="Vorheriger Monat">{{icon "left"}}</a>
<form class="range-form" method="get" action="/guest">
<input type="hidden" name="tid" value="{{.Data.TenantID}}">
<label class="field field-inline"><span>Von</span><input type="date" name="start" value="{{.Data.Start}}"></label>
<label class="field field-inline"><span>Bis</span><input type="date" name="end" value="{{.Data.End}}"></label>
<button class="btn btn-secondary btn-small" type="submit">Anzeigen</button>
</form>
<a class="icon-button" href="/guest?tid={{.Data.TenantID}}&amp;start={{.Data.NextStart}}&amp;end={{.Data.NextEnd}}" title="Nächster Monat">{{icon "right"}}</a>
</div>
<div class="toolbar-group">
<a class="chip" href="/guest?tid={{.Data.TenantID}}">{{icon "calendar"}} Dieser Monat</a>
</div>
</section>
<section class="stat-strip three">
<article class="mini-stat"><span class="mini-stat-label">Gottesdienste</span><strong>{{.Data.ServiceCount}}</strong><small>im gewählten Zeitraum</small></article>
<article class="mini-stat {{if gt .Data.OpenSlots 0}}warn{{end}}"><span class="mini-stat-label">Offene Dienste</span><strong>{{.Data.OpenSlots}}</strong><small>{{plural .Data.OpenSlots "Dienst" "Dienste"}}</small></article>
<article class="mini-stat"><span class="mini-stat-label">Kirchen</span><strong>{{len .Data.Churches}}</strong><small>im öffentlichen Plan</small></article>
</section>
<div class="plan-legend">
<div class="filter-chips" role="group" aria-label="Tage filtern">
<button class="chip active" type="button" data-plan-filter="all">Alle Tage</button>
<button class="chip" type="button" data-plan-filter="services">Mit Gottesdiensten</button>
<button class="chip" type="button" data-plan-filter="open">Nur offene</button>
<button class="chip" type="button" data-plan-filter="feasts">Sonn- &amp; Feiertage</button>
</div>
<div class="legend-items">
<span><i class="swatch sunday"></i>Sonntag</span>
<span><i class="swatch feast"></i>Hochfest</span>
<span><i class="swatch open"></i>Offener Dienst</span>
</div>
</div>
<section class="calendar-card" data-plan-table>
<div class="table-scroll plan-table-desktop">
<table class="calendar-table">
<thead>
<tr>
<th class="col-date">Tag</th>
<th class="col-liturgy">Liturgie &amp; Lesungen</th>
{{range .Data.Churches}}
<th class="col-church">
<span class="church-head" title="{{.Name}} · {{.Address}}">
{{churchGlyph .Symbol .ColorHex}}
<span class="church-head-text"><strong>{{.ShortName}}</strong><small>{{.Name}}</small></span>
</span>
</th>
{{end}}
</tr>
</thead>
<tbody>
{{range $row := .Data.Rows}}
<tr class="plan-row {{if .IsHighFeast}}is-highfeast{{else if .IsSunday}}is-sunday{{else if .IsObligation}}is-obligation{{else if .IsFeast}}is-feast{{end}}"
data-plan-row
data-has-services="{{if .HasServices}}true{{else}}false{{end}}"
data-open="{{.OpenSlots}}"
data-special="{{if .IsSpecialDay}}true{{else}}false{{end}}">
<td class="date-cell">
<div class="date-number">{{dayNumber .Date}}</div>
<div class="date-meta"><span>{{shortWeekday .Date}}</span><span>{{shortMonth .Date}}</span></div>
{{if .LiturgicalDay}}<span class="liturgical-bar" style="background:{{liturgicalColor .LiturgicalDay}}"></span>{{end}}
</td>
<td class="liturgy-cell">
{{if .LiturgicalDay}}
<div class="liturgy-title">
{{feastGlyph .LiturgicalDay.Symbol}}
<strong>{{.LiturgicalDay.DisplayTitle}}</strong>
</div>
<div class="liturgy-meta">
{{if .LiturgicalDay.BadgeText}}<span class="badge badge-rank rank-{{.LiturgicalDay.Rank.ShortLabel}}">{{.LiturgicalDay.BadgeText}}</span>{{end}}
<span class="badge badge-color" style="--badge-color:{{liturgicalColor .LiturgicalDay}}">{{.LiturgicalDay.Color.Label}}</span>
{{if .LiturgicalDay.IsObligation}}<span class="badge badge-burgundy">geboten</span>{{end}}
</div>
{{if not .LiturgicalDay.Readings.IsEmpty}}
<a class="readings" href="https://schott.erzabtei-beuron.de/?datum={{isoDate .Date}}" target="_blank" rel="noopener" title="{{.LiturgicalDay.Readings.FullLabel}} · Tageslesungen bei Schott öffnen">{{.LiturgicalDay.Readings.ShortLabel}}{{icon "external"}}</a>
{{end}}
{{if .LiturgicalDay.Remark}}<div class="liturgy-remark">{{.LiturgicalDay.Remark}}</div>{{end}}
{{else}}
<span class="muted">—</span>
{{end}}
</td>
{{range $.Data.Churches}}
{{$church := .}}
<td class="church-cell">
{{$services := $row.ServicesForChurch $church.ID}}
{{if $services}}
<div class="service-stack">
{{range $services}}
<article class="service-card guest-service {{if .IsFullyStaffed}}staffed{{else}}open{{end}}">
<span class="service-time">{{timeLabel .Service.TimeMinutes}}</span>
<span class="service-title">{{.Service.Title}}{{if eq (printf "%s" .Service.Kind) "special"}}<span class="service-kind">Sonder</span>{{end}}</span>
{{if .Service.Location}}<span class="service-location">{{deref .Service.Location}}</span>{{end}}
<span class="service-people">
{{range .Assignments}}
<span class="person-chip role-{{roleShort .Role}}" title="{{roleTitle .Role}}">{{roleTitle .Role}}</span>
{{end}}
</span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}}
</article>
{{end}}
</div>
{{else}}
<span class="empty-cell">—</span>
{{end}}
</td>
{{end}}
</tr>
{{end}}
</tbody>
</table>
</div>
<div class="plan-mobile-list">
<p class="plan-mobile-hint">Tippen Sie auf einen Tag, um die Gottesdienste zu sehen.</p>
{{range $row := .Data.Rows}}
<details class="plan-day-card {{if .IsHighFeast}}is-highfeast{{else if .IsSunday}}is-sunday{{else if .IsObligation}}is-obligation{{else if .IsFeast}}is-feast{{end}}"
data-plan-row
data-has-services="{{if .HasServices}}true{{else}}false{{end}}"
data-open="{{.OpenSlots}}"
data-special="{{if .IsSpecialDay}}true{{else}}false{{end}}">
<summary class="plan-day-summary">
<span class="day-date">
<span class="date-number">{{dayNumber $row.Date}}</span>
<span class="date-meta"><span>{{shortWeekday $row.Date}}</span><span>{{shortMonth $row.Date}}</span></span>
{{if $row.LiturgicalDay}}<span class="liturgical-bar" style="background:{{liturgicalColor $row.LiturgicalDay}}"></span>{{end}}
</span>
<span class="day-main">
<span class="day-title">
{{if $row.LiturgicalDay}}
{{feastGlyph $row.LiturgicalDay.Symbol}}
<strong>{{$row.LiturgicalDay.DisplayTitle}}</strong>
{{else}}
<strong>Keine Liturgie hinterlegt</strong>
{{end}}
</span>
<span class="day-status">
{{if $row.HasServices}}
<span>{{len $row.Services}} {{plural (len $row.Services) "Gottesdienst" "Gottesdienste"}}</span>
{{if gt $row.OpenSlots 0}}
<span class="day-status-open">{{$row.OpenSlots}} {{plural $row.OpenSlots "Dienst offen" "Dienste offen"}}</span>
{{else}}
<span class="day-status-ok">vollständig besetzt</span>
{{end}}
{{else}}
<span class="day-status-empty">Keine Gottesdienste</span>
{{end}}
</span>
</span>
<span class="day-chevron" aria-hidden="true">{{icon "right"}}</span>
</summary>
<div class="day-details">
{{if $row.LiturgicalDay}}
{{if not $row.LiturgicalDay.Readings.IsEmpty}}
<a class="readings day-readings" href="https://schott.erzabtei-beuron.de/?datum={{isoDate $row.Date}}" target="_blank" rel="noopener" title="{{$row.LiturgicalDay.Readings.FullLabel}} · Tageslesungen bei Schott öffnen">{{$row.LiturgicalDay.Readings.ShortLabel}}{{icon "external"}}</a>
{{end}}
{{if $row.LiturgicalDay.Remark}}<div class="liturgy-remark">{{$row.LiturgicalDay.Remark}}</div>{{end}}
{{end}}
{{range $.Data.Churches}}
{{$church := .}}
{{$services := $row.ServicesForChurch $church.ID}}
{{if $services}}
<div class="day-church">
<div class="day-church-head">
{{churchGlyph .Symbol .ColorHex}}
<span><strong>{{.ShortName}}</strong><small>{{.Name}}</small></span>
</div>
<div class="service-stack">
{{range $services}}
<article class="service-card day-service-card guest-service {{if .IsFullyStaffed}}staffed{{else}}open{{end}}">
<span class="service-time">{{timeLabel .Service.TimeMinutes}}</span>
<span class="service-title">{{.Service.Title}}{{if eq (printf "%s" .Service.Kind) "special"}}<span class="service-kind">Sonder</span>{{end}}</span>
{{if .Service.Location}}<span class="service-location">{{deref .Service.Location}}</span>{{end}}
<span class="service-people">
{{range .Assignments}}
<span class="person-chip role-{{roleShort .Role}}" title="{{roleTitle .Role}}">{{roleTitle .Role}}</span>
{{end}}
</span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}}
</article>
{{end}}
</div>
</div>
{{end}}
{{end}}
{{if not $row.HasServices}}<p class="empty-note">Für diesen Tag sind keine Gottesdienste eingetragen.</p>{{end}}
</div>
</details>
{{end}}
<p class="plan-mobile-empty empty-note" data-plan-mobile-empty hidden>Keine Tage passen zu diesem Filter.</p>
</div>
</section>
<p class="table-note">Gastansicht: Die Einsätze werden nur mit ihrer Rolle angezeigt. Liturgische Daten von www.eucharistiefeier.de, Lesungen verlinkt zu Schott.</p>
</div>
{{end}}
+34 -4
View File
@@ -3,13 +3,40 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}} · LektorenPlan</title> <title>{{.Title}} · Ordo Voluntariorum</title>
<meta name="theme-color" content="#f4efe4"> <meta name="theme-color" content="#f4efe4">
<link rel="stylesheet" href="/static/style.css"> <link rel="stylesheet" href="/static/style.css">
<script defer src="/static/app.js"></script> <script defer src="/static/app.js"></script>
</head> </head>
<body class="{{if not .User}}auth-page{{else}}app-page{{end}}"> <body class="{{if .Guest}}guest-page{{else if not .User}}auth-page{{else}}app-page{{end}}">
{{if .User}} {{if .Guest}}
<div class="guest-shell">
<header class="guest-bar">
<a class="brand" href="/guest" aria-label="Gastzugang Startseite">
<span class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<path d="M8 40h32M12 40V22l12-8 12 8v18"/>
<path d="M24 8v14M20 12h8"/>
<path d="M19 40V31a5 5 0 0 1 10 0v9"/>
<path d="M6 40h36" stroke-dasharray="2 3" stroke-opacity=".45"/>
</svg>
</span>
<span class="brand-text"><strong>Ordo Voluntariorum</strong><small>Gastzugang · nur Lesen</small></span>
</a>
<div class="guest-actions">
<span class="badge badge-gold">Gastzugang</span>
<a class="btn btn-secondary btn-small" href="/login">{{icon "logout"}} Anmelden</a>
</div>
</header>
<main class="content guest-content">
{{template "content" .}}
</main>
<footer class="app-footer guest-foot">
<span>Gastansicht · keine Einstellungen, keine Schreibzugriffe, keine Personennamen</span>
<span>Liturgische Daten: www.eucharistiefeier.de</span>
</footer>
</div>
{{else if .User}}
<div class="app-shell"> <div class="app-shell">
<aside class="sidebar"> <aside class="sidebar">
<a class="brand" href="/plan" aria-label="LektorenPlan Startseite"> <a class="brand" href="/plan" aria-label="LektorenPlan Startseite">
@@ -21,7 +48,7 @@
<path d="M6 40h36" stroke-dasharray="2 3" stroke-opacity=".45"/> <path d="M6 40h36" stroke-dasharray="2 3" stroke-opacity=".45"/>
</svg> </svg>
</span> </span>
<span class="brand-text"><strong>LektorenPlan</strong><small>Pfarreiplanung im Netz</small></span> <span class="brand-text"><strong>Ordo Voluntariorum</strong><small>Homo proponit, Deus disponit.</small></span>
</a> </a>
<button class="sidebar-close icon-button" type="button" data-nav-close aria-label="Navigation schließen">{{icon "close"}}</button> <button class="sidebar-close icon-button" type="button" data-nav-close aria-label="Navigation schließen">{{icon "close"}}</button>
@@ -54,6 +81,9 @@
<a class="nav-link {{if eq .Active "services"}}active{{end}}" href="/services">{{icon "list"}}<span>Gottesdienstordnung</span></a> <a class="nav-link {{if eq .Active "services"}}active{{end}}" href="/services">{{icon "list"}}<span>Gottesdienstordnung</span></a>
<a class="nav-link {{if eq .Active "team"}}active{{end}}" href="/team">{{icon "users"}}<span>Team &amp; Abwesenheiten</span></a> <a class="nav-link {{if eq .Active "team"}}active{{end}}" href="/team">{{icon "users"}}<span>Team &amp; Abwesenheiten</span></a>
<a class="nav-link {{if eq .Active "statistics"}}active{{end}}" href="/statistics">{{icon "chart"}}<span>Statistik</span></a> <a class="nav-link {{if eq .Active "statistics"}}active{{end}}" href="/statistics">{{icon "chart"}}<span>Statistik</span></a>
{{if .IsEditor}}
<a class="nav-link {{if eq .Active "dispatch"}}active{{end}}" href="/dispatch">{{icon "send"}}<span>Versendung</span></a>
{{end}}
<span class="nav-heading">Organisation</span> <span class="nav-heading">Organisation</span>
<a class="nav-link {{if eq .Active "exchange"}}active{{end}}" href="/exchange">{{icon "exchange"}}<span>Austausch</span></a> <a class="nav-link {{if eq .Active "exchange"}}active{{end}}" href="/exchange">{{icon "exchange"}}<span>Austausch</span></a>
+5 -1
View File
@@ -11,7 +11,7 @@
</svg> </svg>
</span> </span>
<div> <div>
<h1>LektorenPlan</h1> <h1>Ordo Voluntariorum</h1>
<p>Gottesdienste, Dienste und Menschen klug zusammenbringen.</p> <p>Gottesdienste, Dienste und Menschen klug zusammenbringen.</p>
</div> </div>
</div> </div>
@@ -48,6 +48,10 @@
</label> </label>
<button class="btn btn-primary btn-block" type="submit">Anmelden</button> <button class="btn btn-primary btn-block" type="submit">Anmelden</button>
</form> </form>
<div class="auth-guest">
<a class="btn btn-secondary btn-block" href="/guest">{{icon "users"}} Gastzugang ohne Anmeldung</a>
<p class="auth-guest-note">Öffentlicher Gottesdienstplan mit liturgischen Angaben – ohne Namen der eingesetzten Personen und ohne Schreibzugriffe.</p>
</div>
{{if .DemoMode}} {{if .DemoMode}}
<div class="demo-accounts"> <div class="demo-accounts">
<span class="demo-accounts-title">Demo-Zugänge</span> <span class="demo-accounts-title">Demo-Zugänge</span>
+38
View File
@@ -50,6 +50,44 @@
</section> </section>
{{end}} {{end}}
{{if .Data.CanEdit}}
<section class="card">
<div class="card-head"><div><span class="eyebrow">Versendung</span><h3>E-Mail-Versand (SMTP)</h3></div>{{if .Data.SMTPConfigured}}<span class="badge badge-green">{{icon "check"}} konfiguriert</span>{{else}}<span class="badge badge-gold">noch nicht konfiguriert</span>{{end}}</div>
<div class="settings-grid">
<div class="settings-copy">
<h4>Zugangsdaten des Postfachs</h4>
<p>Diese Angaben gelten für den aktiven Mandanten und werden für den Versand der Pläne über die Versendungsansicht benötigt. Üblich sind Port 587 mit STARTTLS oder Port 465 mit SSL/TLS.</p>
<p class="muted">Das Passwort wird gespeichert, aber nie wieder angezeigt. Leer lassen, um das bisherige Passwort beizubehalten.</p>
</div>
<div class="settings-fields">
<div class="form-row">
<label class="field"><span class="field-label">SMTP-Server</span><input type="text" name="smtp_host" value="{{.Data.SMTPHost}}" placeholder="smtp.example.org" {{if not .Data.CanEdit}}disabled{{end}}></label>
<label class="field narrow"><span class="field-label">Port</span><input type="number" name="smtp_port" min="0" max="65535" value="{{.Data.SMTPPort}}" placeholder="587" {{if not .Data.CanEdit}}disabled{{end}}></label>
</div>
<label class="field"><span class="field-label">Verschlüsselung</span>
<select name="smtp_encryption" {{if not .Data.CanEdit}}disabled{{end}}>
<option value="starttls" {{if eq .Data.SMTPEncryption "starttls"}}selected{{end}}>STARTTLS (Port 587)</option>
<option value="ssl" {{if eq .Data.SMTPEncryption "ssl"}}selected{{end}}>SSL/TLS (Port 465)</option>
<option value="none" {{if eq .Data.SMTPEncryption "none"}}selected{{end}}>Ohne Verschlüsselung</option>
</select>
</label>
<div class="form-row">
<label class="field"><span class="field-label">Benutzername</span><input type="text" name="smtp_username" value="{{.Data.SMTPUsername}}" autocomplete="off" {{if not .Data.CanEdit}}disabled{{end}}></label>
<label class="field"><span class="field-label">Passwort {{if .Data.SMTPPasswordSet}}<small>gespeichert</small>{{end}}</span><input type="password" name="smtp_password" value="" autocomplete="new-password" placeholder="{{if .Data.SMTPPasswordSet}}•••••••• (unverändert){{end}}" {{if not .Data.CanEdit}}disabled{{end}}></label>
</div>
<div class="form-row">
<label class="field"><span class="field-label">Absenderadresse</span><input type="email" name="smtp_from_address" value="{{.Data.SMTPFromAddress}}" placeholder="pfarramt@example.org" {{if not .Data.CanEdit}}disabled{{end}}></label>
<label class="field"><span class="field-label">Absendername</span><input type="text" name="smtp_from_name" value="{{.Data.SMTPFromName}}" placeholder="Pfarreiengemeinschaft" {{if not .Data.CanEdit}}disabled{{end}}></label>
</div>
{{if .Data.SMTPPasswordSet}}
<label class="check"><input type="checkbox" name="smtp_clear_password" value="1" {{if not .Data.CanEdit}}disabled{{end}}><span>Gespeichertes Passwort entfernen</span></label>
{{end}}
<p class="source-note">{{icon "send"}} Der Versand erfolgt direkt über diesen Server; das Protokoll finden Sie unter „Versendung“.</p>
</div>
</div>
</section>
{{end}}
<section class="card"> <section class="card">
<div class="card-head"><div><span class="eyebrow">Planung</span><h3>Regeln und Gewichtung</h3></div></div> <div class="card-head"><div><span class="eyebrow">Planung</span><h3>Regeln und Gewichtung</h3></div></div>
<div class="settings-grid"> <div class="settings-grid">