diff --git a/Sources/LektorenPlan/PDF/DispatchCoverPDFRenderer.swift b/Sources/LektorenPlan/PDF/DispatchCoverPDFRenderer.swift new file mode 100644 index 0000000..42d78bc --- /dev/null +++ b/Sources/LektorenPlan/PDF/DispatchCoverPDFRenderer.swift @@ -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)! + } +} diff --git a/Sources/LektorenPlan/PDF/PDFMerger.swift b/Sources/LektorenPlan/PDF/PDFMerger.swift new file mode 100644 index 0000000..d9ee0d1 --- /dev/null +++ b/Sources/LektorenPlan/PDF/PDFMerger.swift @@ -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.. Int { + PDFDocument(data: data)?.pageCount ?? 0 + } +} diff --git a/Sources/LektorenPlan/PlanModel.swift b/Sources/LektorenPlan/PlanModel.swift index 0be6a0f..cdc0618 100644 --- a/Sources/LektorenPlan/PlanModel.swift +++ b/Sources/LektorenPlan/PlanModel.swift @@ -9,6 +9,7 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable { case serviceOrder case team case statistics + case dispatch case exchange case settings @@ -20,6 +21,7 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable { case .serviceOrder: "Gottesdienstordnung" case .team: "Lektoren & Helfer" case .statistics: "Statistik" + case .dispatch: "Versendung" case .exchange: "Austausch" case .settings: "Einstellungen" } @@ -31,6 +33,7 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable { case .serviceOrder: "Ordnung" case .team: "Team" case .statistics: "Statistik" + case .dispatch: "Versendung" case .exchange: "Austausch" case .settings: "Einstellungen" } @@ -42,6 +45,7 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable { case .serviceOrder: "building.columns" case .team: "person.2" case .statistics: "chart.xyaxis.line" + case .dispatch: "paperplane" case .exchange: "arrow.left.arrow.right" case .settings: "gearshape" } @@ -53,8 +57,9 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable { case .serviceOrder: 2 case .team: 3 case .statistics: 4 - case .exchange: 5 - case .settings: 6 + case .dispatch: 5 + case .exchange: 6 + case .settings: 7 } } } @@ -144,8 +149,28 @@ struct CandidateSuggestion: Identifiable { 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 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 @Published var section: AppSection = .planning @@ -183,6 +208,10 @@ final class PlanModel: ObservableObject { @Published var databasePath: String @Published var startupWarning: String? @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? @@ -217,6 +246,7 @@ final class PlanModel: ObservableObject { self.showOnlySundaysAndFeasts = value == "1" } loadAll() + loadDispatch() if let warning { alertMessage = warning; alertTitle = "Eingeschränkter Betrieb" } } @@ -829,6 +859,7 @@ final class PlanModel: ObservableObject { let summary = try db.applyPlanExchange(preview.exchange) importPreview = nil loadAll() + loadDispatch() showToast("Import abgeschlossen: \(summary.services) Gottesdienste, \(summary.assignments) Einsätze, \(summary.people) Personen.", kind: .success) } catch { 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 func resetDemoData() { @@ -950,6 +1308,7 @@ final class PlanModel: ObservableObject { db.setSetting("rangeStart", value: DayMath.key(range.start)) db.setSetting("rangeEnd", value: DayMath.key(range.end)) loadAll() + loadDispatch() isResettingData = false showToast( deleteOnly ? "Alle Daten wurden gelöscht." : "Demo-Daten neu aufgebaut.", diff --git a/Sources/LektorenPlan/RootView.swift b/Sources/LektorenPlan/RootView.swift index 243050d..2eb3017 100644 --- a/Sources/LektorenPlan/RootView.swift +++ b/Sources/LektorenPlan/RootView.swift @@ -84,6 +84,9 @@ struct RootView: View { case .statistics: StatisticsView() .transition(.opacity) + case .dispatch: + DispatchView() + .transition(.opacity) case .exchange: ExchangeView() .transition(.opacity) @@ -115,6 +118,7 @@ private struct SidebarView: View { sidebarRow(.serviceOrder) sidebarRow(.team, badge: "\(model.people.filter(\.active).count)") sidebarRow(.statistics) + sidebarRow(.dispatch) } header: { sidebarHeader("Planung") } diff --git a/Sources/LektorenPlan/SnapshotSupport.swift b/Sources/LektorenPlan/SnapshotSupport.swift index c645b19..190e4ef 100644 --- a/Sources/LektorenPlan/SnapshotSupport.swift +++ b/Sources/LektorenPlan/SnapshotSupport.swift @@ -128,6 +128,8 @@ private struct SnapshotContent: View { screen { ExchangeView() } case "settings": screen { SettingsView() } + case "dispatch": + screen { DispatchView() } case "person": PersonEditorSheet(request: PersonEditorRequest(person: model.people.first)) case "detail": diff --git a/Sources/LektorenPlan/Views/DispatchView.swift b/Sources/LektorenPlan/Views/DispatchView.swift new file mode 100644 index 0000000..b5aa94c --- /dev/null +++ b/Sources/LektorenPlan/Views/DispatchView.swift @@ -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 { + Binding( + get: { recipient.preference.channel }, + set: { model.setDispatchChannel($0, for: recipient.person) } + ) + } + + private func variantBinding(_ recipient: DispatchRecipient) -> Binding { + Binding( + get: { recipient.preference.variant }, + set: { model.setDispatchVariant($0, for: recipient.person) } + ) + } + + private func coverBinding(_ recipient: DispatchRecipient) -> Binding { + 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) + } + } + } +} diff --git a/Sources/LektorenPlanCore/AppDatabase.swift b/Sources/LektorenPlanCore/AppDatabase.swift index de90558..c360f13 100644 --- a/Sources/LektorenPlanCore/AppDatabase.swift +++ b/Sources/LektorenPlanCore/AppDatabase.swift @@ -145,6 +145,31 @@ public final class AppDatabase { key TEXT PRIMARY KEY, 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) // Older databases predate the free-text location for special services. @@ -153,7 +178,7 @@ public final class AppDatabase { column: "location", 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 { @@ -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 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 service_templates; DELETE FROM absences; DELETE FROM people; DELETE FROM churches; DELETE FROM liturgical_days; + DELETE FROM dispatch_preferences; DELETE FROM dispatch_log; """) if markDemoSuppressed { try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('suppressDemoSeed', '1')") diff --git a/Sources/LektorenPlanCore/Dispatch.swift b/Sources/LektorenPlanCore/Dispatch.swift new file mode 100644 index 0000000..24c7661 --- /dev/null +++ b/Sources/LektorenPlanCore/Dispatch.swift @@ -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 + } +} diff --git a/Tests/LektorenPlanCoreTests/CoreTests.swift b/Tests/LektorenPlanCoreTests/CoreTests.swift index 843dfdc..ed1def5 100644 --- a/Tests/LektorenPlanCoreTests/CoreTests.swift +++ b/Tests/LektorenPlanCoreTests/CoreTests.swift @@ -95,6 +95,47 @@ final class CoreTests: XCTestCase { 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 { let db = try AppDatabase.makeInMemory(seedDemo: false) let church = Church(id: "c1", name: "Testkirche", shortName: "Test", symbol: .chapel, colorHex: "#000000") diff --git a/web/go.mod b/web/go.mod index 7a673ee..cb6468d 100644 --- a/web/go.mod +++ b/web/go.mod @@ -13,6 +13,8 @@ require ( github.com/google/uuid v1.6.0 // indirect github.com/mattn/go-isatty v0.0.24 // 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 golang.org/x/sys v0.50.0 // indirect modernc.org/libc v1.80.1 // indirect diff --git a/web/go.sum b/web/go.sum index 673fdbb..97fd65e 100644 --- a/web/go.sum +++ b/web/go.sum @@ -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/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= 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/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= diff --git a/web/pdf/cover.go b/web/pdf/cover.go new file mode 100644 index 0000000..a010d4c --- /dev/null +++ b/web/pdf/cover.go @@ -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() +} diff --git a/web/pdf/merge.go b/web/pdf/merge.go new file mode 100644 index 0000000..5b9deb1 --- /dev/null +++ b/web/pdf/merge.go @@ -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 +} diff --git a/web/store/db.go b/web/store/db.go index 21a94b7..acf8eef 100644 --- a/web/store/db.go +++ b/web/store/db.go @@ -250,6 +250,35 @@ CREATE TABLE IF NOT EXISTS tenant_settings ( value TEXT NOT NULL, 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 { @@ -280,7 +309,7 @@ func (s *Store) migrate(ctx context.Context) error { } } 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 { return fmt.Errorf("record schema version: %w", err) } diff --git a/web/store/dispatch.go b/web/store/dispatch.go new file mode 100644 index 0000000..5dbdfb3 --- /dev/null +++ b/web/store/dispatch.go @@ -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 + }) +} diff --git a/web/store/settings.go b/web/store/settings.go index 6e8d6b7..67767f7 100644 --- a/web/store/settings.go +++ b/web/store/settings.go @@ -99,6 +99,8 @@ func (s *Store) DeleteAllTenantData(ctx context.Context, tenantID string) error "DELETE FROM absences WHERE tenant_id=?", "DELETE FROM people 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=?", } for _, statement := range statements { diff --git a/web/web/dispatch_handlers.go b/web/web/dispatch_handlers.go new file mode 100644 index 0000000..c3dad9c --- /dev/null +++ b/web/web/dispatch_handlers.go @@ -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")), + } +} diff --git a/web/web/dispatch_test.go b/web/web/dispatch_test.go new file mode 100644 index 0000000..d0c3acf --- /dev/null +++ b/web/web/dispatch_test.go @@ -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) + } + } +} diff --git a/web/web/guest_handlers.go b/web/web/guest_handlers.go new file mode 100644 index 0000000..9b2bc9f --- /dev/null +++ b/web/web/guest_handlers.go @@ -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) +} diff --git a/web/web/mailer.go b/web/web/mailer.go new file mode 100644 index 0000000..d1318ec --- /dev/null +++ b/web/web/mailer.go @@ -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() +} diff --git a/web/web/mailer_test.go b/web/web/mailer_test.go new file mode 100644 index 0000000..db6651b --- /dev/null +++ b/web/web/mailer_test.go @@ -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) + } +} diff --git a/web/web/render.go b/web/web/render.go index 1d59090..7c12a01 100644 --- a/web/web/render.go +++ b/web/web/render.go @@ -27,6 +27,7 @@ type viewData struct { FlashKind string IsEditor bool IsAdmin bool + Guest bool Version string DemoMode bool LoginQuote string @@ -144,6 +145,9 @@ func templateFunctions() template.FuncMap { "roleTitle": func(role domain.Role) string { return role.Title() }, "rolePlural": func(role domain.Role) string { return role.Plural() }, "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) }, "dioceses": func() any { return dioceseOptions }, "percent": percentLabel, @@ -397,6 +401,8 @@ var iconPaths = map[string]string{ "settings": ``, "shield": ``, "printer": ``, + "send": ``, + "mail": ``, "plus": ``, "left": ``, "right": ``, diff --git a/web/web/server.go b/web/web/server.go index 0dc4ca1..8e4b162 100644 --- a/web/web/server.go +++ b/web/web/server.go @@ -62,7 +62,7 @@ func New(st *store.Store, opts Options) (*Server, error) { funcs := templateFunctions() names := []string{ "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", } 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("POST /login", s.handleLoginPost) + mux.HandleFunc("GET /guest", s.handleGuest) mux.HandleFunc("POST /logout", s.auth(s.handleLogout)) mux.HandleFunc("GET /password", s.auth(s.handlePasswordGet)) 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("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/tenants", s.admin(s.handleAdminTenants)) mux.HandleFunc("POST /admin/tenants/save", s.admin(s.handleAdminTenantSave)) diff --git a/web/web/settings_handlers.go b/web/web/settings_handlers.go index 3650f70..92f36cf 100644 --- a/web/web/settings_handlers.go +++ b/web/web/settings_handlers.go @@ -21,6 +21,14 @@ type settingsPageData struct { DemoReset bool LoginQuote string LoginQuoteSource string + SMTPHost string + SMTPPort string + SMTPUsername string + SMTPPasswordSet bool + SMTPFromAddress string + SMTPFromName string + SMTPEncryption string + SMTPConfigured bool } const ( @@ -101,6 +109,19 @@ func (s *Server) handleSettings(w http.ResponseWriter, r *http.Request, user *st LoginQuote: s.loginQuote(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 == "" { 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{ "planner.replaceExisting": boolSetting(r.FormValue("replace_existing")), "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") } +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 { if value == "1" || value == "on" || value == "true" { return "1" diff --git a/web/web/static/app.js b/web/web/static/app.js index 836c773..b1470eb 100644 --- a/web/web/static/app.js +++ b/web/web/static/app.js @@ -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 ------------------------------------ */ function initSubmitGuards() { document.querySelectorAll("form").forEach(function (form) { @@ -195,6 +219,7 @@ initPersonSearch(); initFileDrop(); initRangeOutputs(); + initDispatchBulk(); initSubmitGuards(); }); })(); diff --git a/web/web/static/style.css b/web/web/static/style.css index 2382e42..dabb491 100644 --- a/web/web/static/style.css +++ b/web/web/static/style.css @@ -812,6 +812,65 @@ hr { border: 0; border-top: 1px solid var(--line); margin: 1rem 0; } .error-page h2 { margin-bottom: .35rem; } .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 ---------- */ [data-plan-row].filtered { display: none; } [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; } .church-overview { grid-template-columns: 1fr; } .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 { diff --git a/web/web/templates/dispatch.html b/web/web/templates/dispatch.html new file mode 100644 index 0000000..0aadb2e --- /dev/null +++ b/web/web/templates/dispatch.html @@ -0,0 +1,215 @@ +{{define "content"}} +
+
+
+ Planung · Versendung +

Den Plan an alle Empfänger bringen

+

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.

+
+
+ {{if .Data.SMTPConfigured}} + {{icon "mail"}} SMTP bereit · {{.Data.SMTPFrom}} + {{else}} + {{icon "mail"}} SMTP nicht konfiguriert + {{end}} +
+
+ +
+
+ {{icon "left"}} +
+ + + +
+ {{icon "right"}} +
+
+ {{rangeLong .Data.Range}} + {{icon "calendar"}} Dieser Monat +
+
+ +
+
E-Mail{{.Data.EmailCount}}Empfänger mit Adresse
+
Ausdruck{{.Data.PrintCount}}im Sammel-PDF
+
Ohne Versand{{.Data.NoneCount}}bewusst ausgelassen
+
Offene Dienste{{.Data.OpenSlots}}in {{.Data.ServiceCount}} Gottesdiensten
+
+ + {{if not .Data.SMTPConfigured}} +
+ {{icon "mail"}} +
+ E-Mail-Versand noch nicht eingerichtet +

Hinterlegen Sie die SMTP-Zugangsdaten in den Einstellungen, damit E-Mails direkt verschickt werden können. Ausdrucke funktionieren bereits ohne SMTP.

+
+ {{icon "settings"}} Zu den Einstellungen +
+ {{end}} + +
+ + + + +
+
+
Texte

Anschreiben

+ Platzhalter {start} und {end} +
+
+
+

Ein Text für alle

+

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 {start} und {end} werden beim Versand durch den Planungszeitraum ersetzt.

+

Ein leer gelassenes Einleitungsfeld stellt den Standardtext wieder her.

+
+
+ + +
+
+
+ +
+
+
Empfänger

Versandweg je Person

+
+ + + +
+
+
+ + + + + + + + + + + + {{range .Data.People}} + {{$person := .Person}} + {{$effective := .Effective}} + + + + + + + + {{else}} + + {{end}} + +
PersonEinsätzeVersandwegListeVorblatt
+
+ {{$person.FullName}} + {{$person.RoleLabel}} + {{if $person.Email}} + {{$person.Email}} + {{else}} + keine E-Mail-Adresse hinterlegt + {{end}} +
+
+ {{if .Assignments}} +
+ {{.AssignmentCount}} {{if eq .AssignmentCount 1}}Einsatz{{else}}Einsätze{{end}} +
    + {{range .Assignments}} +
  • {{.DateLabel}}{{.TimeLabel}}{{.Church}}{{.RoleLabel}}
  • + {{end}} +
+
+ {{else}} + keine Einsätze + {{end}} +
+ + {{if and (eq .Channel "email") (not $person.Email)}}ohne Adresse → Ausdruck{{end}} + + + + +

Im aktiven Mandanten sind noch keine aktiven Personen hinterlegt.

+
+

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.

+
+ + + +
+
+
+ + {{with .Data.LastEntry}} +
+
+
Letzte Versendung

{{rangeShort $.Data.Range}} · {{.CreatedAt.Format "02.01.2006, 15:04"}} Uhr

+ {{len $.Data.LastBatch}} {{if eq (len $.Data.LastBatch) 1}}Eintrag{{else}}Einträge{{end}} +
+
+
Zeitraum{{shortDate .RangeStart}} – {{shortDate .RangeEnd}}
+
Ausgelöst von{{if .CreatedBy}}{{.CreatedBy}}{{else}}unbekannt{{end}}
+
Aktion{{statusLabel .Status}}
+
+
    + {{range $.Data.LastBatch}} +
  • + {{.PersonName}} + {{channelLabel .Channel}} · {{variantLabel .Variant}}{{if .Cover}} · mit Vorblatt{{end}} + {{statusLabel .Status}} + {{if .Detail}}{{.Detail}}{{end}} +
  • + {{end}} +
+
+ {{end}} + + {{if .Data.History}} +
+
Protokoll

Versendungen im Überblick

{{len .Data.History}}
+
+ + + + + + {{range .Data.History}} + + + + + + + + + + {{end}} + +
ZeitpunktZeitraumPersonKanalListeStatusVon
{{.CreatedAt.Format "02.01.2006, 15:04"}}{{shortDate .RangeStart}} – {{shortDate .RangeEnd}}{{.PersonName}}{{if .Email}}
{{.Email}}{{end}}
{{channelLabel .Channel}}{{if .Cover}}
mit Vorblatt{{end}}
{{variantLabel .Variant}}{{statusLabel .Status}}{{.CreatedBy}}
+
+
+ {{end}} +
+{{end}} diff --git a/web/web/templates/guest.html b/web/web/templates/guest.html new file mode 100644 index 0000000..6e1909e --- /dev/null +++ b/web/web/templates/guest.html @@ -0,0 +1,220 @@ +{{define "content"}} +
+
+
+ Öffentlicher Plan · {{.Data.TenantName}} +

{{rangeLong .Data.Range}}

+

Alle Gottesdienste mit liturgischen Angaben und Lesungsverweisen – ohne Namen der eingesetzten Personen, ohne Einstellungen und ohne Schreibzugriffe.

+
+
+ {{if gt (len .Data.Tenants) 1}} +
+ + +
+ {{end}} + Nur Lesen +
+
+ +
+
+ {{icon "left"}} +
+ + + + +
+ {{icon "right"}} +
+ +
+ +
+
Gottesdienste{{.Data.ServiceCount}}im gewählten Zeitraum
+
Offene Dienste{{.Data.OpenSlots}}{{plural .Data.OpenSlots "Dienst" "Dienste"}}
+
Kirchen{{len .Data.Churches}}im öffentlichen Plan
+
+ +
+
+ + + + +
+
+ Sonntag + Hochfest + Offener Dienst +
+
+ +
+
+ + + + + + {{range .Data.Churches}} + + {{end}} + + + + {{range $row := .Data.Rows}} + + + + {{range $.Data.Churches}} + {{$church := .}} + + {{end}} + + {{end}} + +
TagLiturgie & Lesungen + + {{churchGlyph .Symbol .ColorHex}} + {{.ShortName}}{{.Name}} + +
+
{{dayNumber .Date}}
+
{{shortWeekday .Date}}{{shortMonth .Date}}
+ {{if .LiturgicalDay}}{{end}} +
+ {{if .LiturgicalDay}} +
+ {{feastGlyph .LiturgicalDay.Symbol}} + {{.LiturgicalDay.DisplayTitle}} +
+
+ {{if .LiturgicalDay.BadgeText}}{{.LiturgicalDay.BadgeText}}{{end}} + {{.LiturgicalDay.Color.Label}} + {{if .LiturgicalDay.IsObligation}}geboten{{end}} +
+ {{if not .LiturgicalDay.Readings.IsEmpty}} + {{.LiturgicalDay.Readings.ShortLabel}}{{icon "external"}} + {{end}} + {{if .LiturgicalDay.Remark}}
{{.LiturgicalDay.Remark}}
{{end}} + {{else}} + — + {{end}} +
+ {{$services := $row.ServicesForChurch $church.ID}} + {{if $services}} +
+ {{range $services}} +
+ {{timeLabel .Service.TimeMinutes}} + {{.Service.Title}}{{if eq (printf "%s" .Service.Kind) "special"}}Sonder{{end}} + {{if .Service.Location}}{{deref .Service.Location}}{{end}} + + {{range .Assignments}} + {{roleTitle .Role}} + {{end}} + + {{if not .IsFullyStaffed}}{{plural .OpenSlots "Platz offen" "Plätze offen"}}{{end}} +
+ {{end}} +
+ {{else}} + — + {{end}} +
+
+ +
+

Tippen Sie auf einen Tag, um die Gottesdienste zu sehen.

+ {{range $row := .Data.Rows}} +
+ + + {{dayNumber $row.Date}} + {{shortWeekday $row.Date}}{{shortMonth $row.Date}} + {{if $row.LiturgicalDay}}{{end}} + + + + {{if $row.LiturgicalDay}} + {{feastGlyph $row.LiturgicalDay.Symbol}} + {{$row.LiturgicalDay.DisplayTitle}} + {{else}} + Keine Liturgie hinterlegt + {{end}} + + + {{if $row.HasServices}} + {{len $row.Services}} {{plural (len $row.Services) "Gottesdienst" "Gottesdienste"}} + {{if gt $row.OpenSlots 0}} + {{$row.OpenSlots}} {{plural $row.OpenSlots "Dienst offen" "Dienste offen"}} + {{else}} + vollständig besetzt + {{end}} + {{else}} + Keine Gottesdienste + {{end}} + + + + +
+ {{if $row.LiturgicalDay}} + {{if not $row.LiturgicalDay.Readings.IsEmpty}} + {{$row.LiturgicalDay.Readings.ShortLabel}}{{icon "external"}} + {{end}} + {{if $row.LiturgicalDay.Remark}}
{{$row.LiturgicalDay.Remark}}
{{end}} + {{end}} + {{range $.Data.Churches}} + {{$church := .}} + {{$services := $row.ServicesForChurch $church.ID}} + {{if $services}} +
+
+ {{churchGlyph .Symbol .ColorHex}} + {{.ShortName}}{{.Name}} +
+
+ {{range $services}} +
+ {{timeLabel .Service.TimeMinutes}} + {{.Service.Title}}{{if eq (printf "%s" .Service.Kind) "special"}}Sonder{{end}} + {{if .Service.Location}}{{deref .Service.Location}}{{end}} + + {{range .Assignments}} + {{roleTitle .Role}} + {{end}} + + {{if not .IsFullyStaffed}}{{plural .OpenSlots "Platz offen" "Plätze offen"}}{{end}} +
+ {{end}} +
+
+ {{end}} + {{end}} + {{if not $row.HasServices}}

Für diesen Tag sind keine Gottesdienste eingetragen.

{{end}} +
+
+ {{end}} + +
+
+

Gastansicht: Die Einsätze werden nur mit ihrer Rolle angezeigt. Liturgische Daten von www.eucharistiefeier.de, Lesungen verlinkt zu Schott.

+
+{{end}} diff --git a/web/web/templates/layout.html b/web/web/templates/layout.html index bd436ea..4ff371d 100644 --- a/web/web/templates/layout.html +++ b/web/web/templates/layout.html @@ -3,13 +3,40 @@ - {{.Title}} · LektorenPlan + {{.Title}} · Ordo Voluntariorum - -{{if .User}} + +{{if .Guest}} +
+
+ + + Ordo VoluntariorumGastzugang · nur Lesen + +
+ Gastzugang + {{icon "logout"}} Anmelden +
+
+
+ {{template "content" .}} +
+
+ Gastansicht · keine Einstellungen, keine Schreibzugriffe, keine Personennamen + Liturgische Daten: www.eucharistiefeier.de +
+
+{{else if .User}}
@@ -48,6 +48,10 @@ +
+ {{icon "users"}} Gastzugang ohne Anmeldung +

Öffentlicher Gottesdienstplan mit liturgischen Angaben – ohne Namen der eingesetzten Personen und ohne Schreibzugriffe.

+
{{if .DemoMode}}
Demo-Zugänge diff --git a/web/web/templates/settings.html b/web/web/templates/settings.html index 81690d7..4f55cbd 100644 --- a/web/web/templates/settings.html +++ b/web/web/templates/settings.html @@ -50,6 +50,44 @@ {{end}} + {{if .Data.CanEdit}} +
+
Versendung

E-Mail-Versand (SMTP)

{{if .Data.SMTPConfigured}}{{icon "check"}} konfiguriert{{else}}noch nicht konfiguriert{{end}}
+
+
+

Zugangsdaten des Postfachs

+

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.

+

Das Passwort wird gespeichert, aber nie wieder angezeigt. Leer lassen, um das bisherige Passwort beizubehalten.

+
+
+
+ + +
+ +
+ + +
+
+ + +
+ {{if .Data.SMTPPasswordSet}} + + {{end}} +

{{icon "send"}} Der Versand erfolgt direkt über diesen Server; das Protokoll finden Sie unter „Versendung“.

+
+
+
+ {{end}} +
Planung

Regeln und Gewichtung