1. Version Versendung

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

No files matched your search

@@ -0,0 +1,367 @@
import AppKit
import CoreGraphics
import LektorenPlanCore
/// One assignment of a recipient, as shown on the cover sheet.
struct DispatchAssignment: Identifiable, Hashable {
var id: String
var date: Date
var timeMinutes: Int
var church: String
var title: String
var role: Role
var dateLabel: String {
"\(DayMath.shortWeekdayName(date)), \(DayMath.dayNumber(date)).\(DayMath.month(date)).\(DayMath.year(date))"
}
var timeLabel: String {
DayMath.timeString(minutes: timeMinutes)
}
}
/// Data for the personal cover letter that precedes a printed plan.
struct DispatchCoverData {
var range: DayRange
var person: Person
var intro: String
var greeting: String
var assignments: [DispatchAssignment]
var generatedAt: Date
}
/// Renders the personalized A4 cover sheet for dispatch packets.
enum DispatchCoverPDFRenderer {
private static let pageWidth: CGFloat = 595
private static let pageHeight: CGFloat = 842
private static let margin: CGFloat = 48
private static let contentWidth: CGFloat = pageWidth - margin * 2
private static let footerHeight: CGFloat = 30
private static let contentBottom: CGFloat = pageHeight - margin - footerHeight
// MARK: - Colours
private static let ink = NSColor(calibratedRed: 0.12, green: 0.135, blue: 0.155, alpha: 1)
private static let secondaryInk = NSColor(calibratedRed: 0.38, green: 0.385, blue: 0.39, alpha: 1)
private static let tertiaryInk = NSColor(calibratedRed: 0.52, green: 0.51, blue: 0.49, alpha: 1)
private static let lineColor = NSColor(calibratedRed: 0.845, green: 0.825, blue: 0.79, alpha: 1)
private static let accent = NSColor(calibratedRed: 0.18, green: 0.36, blue: 0.34, alpha: 1)
private static let headerWash = NSColor(calibratedRed: 0.965, green: 0.945, blue: 0.905, alpha: 1)
// MARK: - Fonts
private static func serif(_ size: CGFloat, bold: Bool = false) -> NSFont {
let name = bold ? "NewYork-Semibold" : "NewYork-Regular"
return NSFont(name: name, size: size) ?? NSFont.systemFont(ofSize: size, weight: bold ? .semibold : .regular)
}
private static func sans(_ size: CGFloat, weight: NSFont.Weight = .regular) -> NSFont {
NSFont.systemFont(ofSize: size, weight: weight)
}
// MARK: - Render
static func render(_ data: DispatchCoverData) -> Data {
let output = NSMutableData()
var mediaBox = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
guard let consumer = CGDataConsumer(data: output as CFMutableData),
let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)
else { return Data() }
storedContext = context
defer { storedContext = nil }
var pageIndex = 0
func beginPage() {
context.beginPDFPage(nil)
context.saveGState()
context.translateBy(x: 0, y: pageHeight)
context.scaleBy(x: 1, y: -1)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
}
func endPage() {
drawText(
"LektorenPlan · \(data.person.fullName) · \(data.range.shortTitle)",
in: CGRect(x: margin, y: pageHeight - margin + 6, width: contentWidth, height: 10),
font: sans(6.5),
color: tertiaryInk
)
drawText(
"Seite \(pageIndex + 1)",
in: CGRect(x: margin, y: pageHeight - margin + 6, width: contentWidth, height: 10),
font: sans(6.5),
color: tertiaryInk,
alignment: .right
)
NSGraphicsContext.restoreGraphicsState()
context.restoreGState()
context.endPDFPage()
pageIndex += 1
}
beginPage()
var cursorY = margin
// Header ------------------------------------------------------------
drawText(
"LEKTORENPLAN · GOTTESDIENSTPLAN",
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 10),
font: sans(7, weight: .bold),
color: accent
)
cursorY += 8
drawText(
"Gottesdienstplan",
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 26),
font: serif(20, bold: true),
color: ink
)
cursorY += 24
drawText(
data.range.title,
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 14),
font: sans(10),
color: secondaryInk
)
cursorY += 20
context.setStrokeColor(lineColor.cgColor)
context.setLineWidth(0.8)
context.move(to: CGPoint(x: margin, y: cursorY))
context.addLine(to: CGPoint(x: pageWidth - margin, y: cursorY))
context.strokePath()
cursorY += 22
// Recipient ---------------------------------------------------------
drawText(
"EMPFÄNGER",
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 9),
font: sans(6.5, weight: .bold),
color: tertiaryInk
)
cursorY += 10
drawText(
data.person.fullName,
in: CGRect(x: margin, y: cursorY, width: contentWidth - 150, height: 19),
font: serif(13, bold: true),
color: ink
)
drawText(
"Erstellt am \(DayMath.longString(data.generatedAt))",
in: CGRect(x: margin, y: cursorY + 3, width: contentWidth, height: 12),
font: sans(7.5),
color: tertiaryInk,
alignment: .right
)
cursorY += 18
if !data.person.email.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
drawText(
data.person.email,
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 12),
font: sans(8),
color: secondaryInk
)
cursorY += 14
}
cursorY += 14
// Letter text -------------------------------------------------------
let introFont = serif(11.5)
let introLineHeight: CGFloat = 16
for line in wrappedLines(data.intro, font: introFont, width: contentWidth) {
if cursorY + introLineHeight > contentBottom {
endPage()
beginPage()
cursorY = margin
}
drawText(
line,
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: introLineHeight),
font: introFont,
color: ink
)
cursorY += introLineHeight
}
cursorY += 14
// Assignment table --------------------------------------------------
if cursorY + 70 > contentBottom {
endPage()
beginPage()
cursorY = margin
}
drawText(
"Ihre Einsätze im Planungszeitraum",
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 18),
font: serif(12.5, bold: true),
color: ink
)
cursorY += 21
let columns: [(title: String, width: CGFloat)] = [
("Tag", 150), ("Zeit", 54), ("Ort", 120), ("Dienst", contentWidth - 150 - 54 - 120)
]
if data.assignments.isEmpty {
for line in wrappedLines(
"Für Sie sind in diesem Zeitraum keine Einsätze eingetragen.",
font: serif(10.5),
width: contentWidth
) {
if cursorY + 14 > contentBottom {
endPage()
beginPage()
cursorY = margin
}
drawText(line, in: CGRect(x: margin, y: cursorY, width: contentWidth, height: 14),
font: serif(10.5), color: secondaryInk)
cursorY += 14
}
cursorY += 8
} else {
contextFill(CGRect(x: margin, y: cursorY, width: contentWidth, height: 16), color: headerWash)
var columnX = margin + 4
for column in columns {
drawText(
column.title.uppercased(),
in: CGRect(x: columnX, y: cursorY + 4, width: column.width - 6, height: 9),
font: sans(6.4, weight: .bold),
color: tertiaryInk
)
columnX += column.width
}
cursorY += 16
contextLine(y: cursorY)
for assignment in data.assignments {
if cursorY + 18 > contentBottom {
endPage()
beginPage()
cursorY = margin
}
let values = [
assignment.dateLabel,
assignment.timeLabel,
assignment.church,
"\(assignment.role.title) · \(assignment.title)"
]
columnX = margin + 4
for (index, column) in columns.enumerated() {
drawText(
values[index],
in: CGRect(x: columnX, y: cursorY + 4.5, width: column.width - 6, height: 12),
font: sans(7.8),
color: ink
)
columnX += column.width
}
cursorY += 18
context.setStrokeColor(lineColor.withAlphaComponent(0.65).cgColor)
context.setLineWidth(0.4)
context.move(to: CGPoint(x: margin, y: cursorY))
context.addLine(to: CGPoint(x: pageWidth - margin, y: cursorY))
context.strokePath()
}
cursorY += 14
}
// Greeting ----------------------------------------------------------
if !data.greeting.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
for line in wrappedLines(data.greeting, font: introFont, width: contentWidth) {
if cursorY + introLineHeight > contentBottom {
endPage()
beginPage()
cursorY = margin
}
drawText(
line,
in: CGRect(x: margin, y: cursorY, width: contentWidth, height: introLineHeight),
font: introFont,
color: ink
)
cursorY += introLineHeight
}
}
endPage()
context.closePDF()
return output as Data
}
// MARK: - Text helpers
private static func wrappedLines(_ text: String, font: NSFont, width: CGFloat) -> [String] {
let paragraphs = text.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
var lines: [String] = []
for paragraph in paragraphs {
let trimmed = paragraph.trimmingCharacters(in: .whitespaces)
if trimmed.isEmpty {
lines.append("")
continue
}
var current = ""
for word in trimmed.split(separator: " ", omittingEmptySubsequences: true) {
let candidate = current.isEmpty ? String(word) : current + " " + word
if measure(candidate, font: font) <= width {
current = candidate
} else {
if !current.isEmpty { lines.append(current) }
current = String(word)
}
}
if !current.isEmpty { lines.append(current) }
}
return lines
}
private static func measure(_ text: String, font: NSFont) -> CGFloat {
(text as NSString).size(withAttributes: [.font: font]).width
}
@discardableResult
private static func drawText(
_ text: String,
in rect: CGRect,
font: NSFont,
color: NSColor,
alignment: NSTextAlignment = .left
) -> CGFloat {
guard !text.isEmpty else { return 0 }
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = alignment
paragraph.lineBreakMode = .byTruncatingTail
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: color,
.paragraphStyle: paragraph
]
NSAttributedString(string: text, attributes: attributes).draw(
with: CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height),
options: [.usesLineFragmentOrigin, .usesFontLeading]
)
return rect.height
}
private static func contextLine(y: CGFloat) {
context.setStrokeColor(lineColor.withAlphaComponent(0.85).cgColor)
context.setLineWidth(0.6)
context.move(to: CGPoint(x: margin, y: y))
context.addLine(to: CGPoint(x: pageWidth - margin, y: y))
context.strokePath()
}
private static func contextFill(_ rect: CGRect, color: NSColor) {
context.setFillColor(color.cgColor)
context.fill(rect)
}
nonisolated(unsafe) private static var storedContext: CGContext?
private static var context: CGContext {
storedContext ?? CGContext(data: nil, width: 1, height: 1, bitsPerComponent: 8,
bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
}
}
+22
View File
@@ -0,0 +1,22 @@
import Foundation
import PDFKit
/// Concatenates several PDF documents page by page. Used for the printable
/// dispatch packet: cover sheet and selected list for each recipient.
enum PDFMerger {
static func merge(_ documents: [Data]) -> Data {
let output = PDFDocument()
for data in documents {
guard let document = PDFDocument(data: data) else { continue }
for index in 0..<document.pageCount {
guard let page = document.page(at: index) else { continue }
output.insert(page, at: output.pageCount)
}
}
return output.dataRepresentation() ?? Data()
}
static func pageCount(_ data: Data) -> Int {
PDFDocument(data: data)?.pageCount ?? 0
}
}
+361 -2
View File
@@ -9,6 +9,7 @@ enum AppSection: String, CaseIterable, Identifiable, Hashable {
case serviceOrder
case 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<Void, Never>?
@@ -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.",
+4
View File
@@ -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")
}
@@ -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":
@@ -0,0 +1,540 @@
import SwiftUI
import LektorenPlanCore
/// Dispatch view: decides who receives the plan of the current period, by
/// e-mail (opened in the default mail client with a personal PDF attachment)
/// or as one combined printable packet.
struct DispatchView: View {
@EnvironmentObject private var model: PlanModel
private static let timestampFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "de_DE")
formatter.dateFormat = "dd.MM.yyyy, HH:mm"
return formatter
}()
private var recipients: [DispatchRecipient] { model.dispatchRecipients }
private var emailRecipients: [DispatchRecipient] {
recipients.filter { $0.effectiveChannel == .email }
}
private var printRecipients: [DispatchRecipient] {
recipients.filter { $0.effectiveChannel == .print }
}
var body: some View {
VStack(spacing: 14) {
PageHeader(
eyebrow: "Planung",
title: "Versendung",
subtitle: "Den Plan des aktuellen Zeitraums persönlich per E-Mail oder als Sammel-Ausdruck weitergeben."
) {
HStack(spacing: 8) {
SecondaryActionButton(title: "Einstellungen speichern", icon: "square.and.arrow.down") {
model.saveDispatchSettings()
}
SecondaryActionButton(
title: "Ausdruck-PDF",
icon: "printer",
action: { model.createDispatchPrintPDF() },
disabled: printRecipients.isEmpty
)
PrimaryActionButton(
title: "E-Mails öffnen (\(emailRecipients.count))",
icon: "envelope",
action: { model.openDispatchEmails() },
disabled: emailRecipients.isEmpty
)
}
}
ScrollView {
VStack(alignment: .leading, spacing: 14) {
if model.people.isEmpty {
SurfaceCard {
EmptyStateView(
icon: "person.2.slash",
title: "Noch keine Personen",
message: "Legen Sie zuerst Lektoren und Kommunionhelfer an, um den Plan zu versenden.",
actionTitle: "Zum Team",
action: { model.section = .team }
)
}
} else {
rangeBanner
textsCard
recipientsCard
if !model.dispatchLastBatch.isEmpty {
lastBatchCard
}
if !model.dispatchLog.isEmpty {
historyCard
}
}
}
.padding(.bottom, 16)
}
}
.padding(.horizontal, 22)
.padding(.top, 30)
.padding(.bottom, 18)
}
// MARK: - Range
private var rangeBanner: some View {
SurfaceCard(padding: 13, radius: 14, background: LP.card.opacity(0.9)) {
HStack(spacing: 12) {
Image(systemName: "calendar.badge.clock")
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(LP.accent)
.frame(width: 30, height: 30)
.background(Circle().fill(LP.accent.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text("Planungszeitraum")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
Text(model.range.title)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(LP.ink)
}
Spacer()
HStack(spacing: 14) {
countLabel("\(recipients.count)", "Empfänger")
countLabel("\(emailRecipients.count)", "per E-Mail")
countLabel("\(printRecipients.count)", "als Ausdruck")
}
SecondaryActionButton(title: "Zeitraum ändern", icon: "slider.horizontal.3") {
model.section = .planning
}
}
}
}
private func countLabel(_ value: String, _ label: String) -> some View {
VStack(alignment: .trailing, spacing: 0) {
Text(value)
.font(.system(size: 13, weight: .bold, design: .rounded))
.foregroundStyle(LP.ink)
Text(label)
.font(.system(size: 8))
.foregroundStyle(LP.inkTertiary)
}
}
// MARK: - Texts
private var textsCard: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
cardHeader(
icon: "text.alignleft",
title: "Anschreiben",
subtitle: "Gilt einheitlich für alle E-Mails und Vorblätter",
tint: LP.accent
)
HStack(alignment: .top, spacing: 14) {
VStack(alignment: .leading, spacing: 5) {
Text("Einleitung")
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(LP.inkTertiary)
TextEditor(text: $model.dispatchIntro)
.font(.system(size: 11.5))
.scrollContentBackground(.hidden)
.padding(8)
.frame(minHeight: 108)
.background(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.fill(LP.cardMuted)
)
.overlay(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.strokeBorder(LP.line.opacity(0.8), lineWidth: 1)
)
}
VStack(alignment: .leading, spacing: 5) {
Text("Abschlussgruß")
.font(.system(size: 9.5, weight: .bold, design: .rounded))
.tracking(0.8)
.foregroundStyle(LP.inkTertiary)
TextEditor(text: $model.dispatchGreeting)
.font(.system(size: 11.5))
.scrollContentBackground(.hidden)
.padding(8)
.frame(minHeight: 108)
.background(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.fill(LP.cardMuted)
)
.overlay(
RoundedRectangle(cornerRadius: 9, style: .continuous)
.strokeBorder(LP.line.opacity(0.8), lineWidth: 1)
)
}
.frame(width: 260)
}
HStack(spacing: 6) {
Image(systemName: "curlybraces")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(LP.inkTertiary)
Text("Platzhalter {start} und {end} werden beim Versand durch „\(DayMath.mediumString(model.range.start))“ und „\(DayMath.mediumString(model.range.end))“ ersetzt. Zwischen Einleitung und Gruß steht die persönliche Einsatzübersicht.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
}
// MARK: - Recipients
private var recipientsCard: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 12) {
HStack(alignment: .top) {
cardHeader(
icon: "paperplane",
title: "Empfänger",
subtitle: "Kanal, Liste und Vorblatt je Person",
tint: LP.burgundy
)
Spacer()
bulkActions
}
HStack(spacing: 8) {
Image(systemName: "info.circle")
.font(.system(size: 10, weight: .semibold))
.foregroundStyle(LP.accent)
Text("Ohne hinterlegte E-Mail-Adresse wird automatisch gedruckt. E-Mails werden als Entwurf im Standard-Mailprogramm geöffnet – mit persönlichem Text und dem gewählten PDF.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.fixedSize(horizontal: false, vertical: true)
}
recipientsHeader
Hairline()
ForEach(recipients) { recipient in
recipientRow(recipient)
if recipient.id != recipients.last?.id {
Hairline()
}
}
}
}
}
private var bulkActions: some View {
HStack(spacing: 6) {
bulkButton("Alle E-Mail", icon: "envelope") {
model.setDispatchChannelForAll(.email)
}
bulkButton("Alle Ausdruck", icon: "printer") {
model.setDispatchChannelForAll(.print)
}
bulkButton("Alle kompakt", icon: "list.bullet") {
for recipient in recipients {
model.setDispatchVariant(.compact, for: recipient.person)
}
}
bulkButton("Alle ausführlich", icon: "doc.text") {
for recipient in recipients {
model.setDispatchVariant(.full, for: recipient.person)
}
}
}
}
private func bulkButton(_ title: String, icon: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
HStack(spacing: 4) {
Image(systemName: icon)
.font(.system(size: 9, weight: .semibold))
Text(title)
.font(.system(size: 9.5, weight: .medium))
}
.foregroundStyle(LP.inkSecondary)
.padding(.horizontal, 8)
.padding(.vertical, 5)
.background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(LP.cardMuted))
.overlay(
RoundedRectangle(cornerRadius: 7, style: .continuous)
.strokeBorder(LP.line.opacity(0.7), lineWidth: 0.8)
)
}
.buttonStyle(.plain)
}
private var recipientsHeader: some View {
HStack(spacing: 10) {
Text("PERSON")
.frame(maxWidth: .infinity, alignment: .leading)
Text("E-MAIL-ADRESSE")
.frame(width: 168, alignment: .leading)
Text("KANAL")
.frame(width: 200, alignment: .leading)
Text("LISTE")
.frame(width: 136, alignment: .leading)
Text("VORBLATT")
.frame(width: 66, alignment: .center)
}
.font(.system(size: 8.5, weight: .bold, design: .rounded))
.tracking(0.7)
.foregroundStyle(LP.inkTertiary)
.padding(.horizontal, 4)
}
private func recipientRow(_ recipient: DispatchRecipient) -> some View {
HStack(spacing: 10) {
HStack(spacing: 9) {
Avatar(
initials: recipient.person.initials,
color: recipient.person.roles.contains(.lector) ? LP.accent : LP.burgundy,
size: 26
)
VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 6) {
Text(recipient.person.fullName)
.font(.system(size: 11.5, weight: .semibold))
.foregroundStyle(LP.ink)
.lineLimit(1)
if !recipient.assignments.isEmpty {
TinyBadge(
text: "\(recipient.assignments.count)",
color: recipient.effectiveChannel == .email ? LP.accent : LP.burgundy
)
}
}
Text(recipient.person.roleLabel)
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
.lineLimit(1)
}
Spacer(minLength: 4)
}
.frame(maxWidth: .infinity, alignment: .leading)
Text(recipient.hasEmail ? recipient.person.email : "keine Adresse")
.font(.system(size: 10))
.foregroundStyle(recipient.hasEmail ? LP.inkSecondary : LP.inkTertiary)
.lineLimit(1)
.truncationMode(.middle)
.frame(width: 168, alignment: .leading)
Picker("", selection: channelBinding(recipient)) {
ForEach(channelOptions(for: recipient)) { channel in
Text(channel.title).tag(channel)
}
}
.labelsHidden()
.pickerStyle(.segmented)
.frame(width: 200)
Picker("", selection: variantBinding(recipient)) {
ForEach(PlanListVariant.allCases) { variant in
Text(variant.title).tag(variant)
}
}
.labelsHidden()
.pickerStyle(.menu)
.frame(width: 136)
Toggle("", isOn: coverBinding(recipient))
.labelsHidden()
.toggleStyle(.checkbox)
.frame(width: 66)
.disabled(recipient.effectiveChannel == .none)
.help("Anschreiben als Vorblatt voranstellen")
}
.padding(.horizontal, 4)
.padding(.vertical, 5)
.opacity(recipient.effectiveChannel == .none ? 0.55 : 1)
}
private func channelOptions(for recipient: DispatchRecipient) -> [DispatchChannel] {
recipient.hasEmail ? [.email, .print, .none] : [.print, .none]
}
private func channelBinding(_ recipient: DispatchRecipient) -> Binding<DispatchChannel> {
Binding(
get: { recipient.preference.channel },
set: { model.setDispatchChannel($0, for: recipient.person) }
)
}
private func variantBinding(_ recipient: DispatchRecipient) -> Binding<PlanListVariant> {
Binding(
get: { recipient.preference.variant },
set: { model.setDispatchVariant($0, for: recipient.person) }
)
}
private func coverBinding(_ recipient: DispatchRecipient) -> Binding<Bool> {
Binding(
get: { recipient.preference.cover },
set: { model.setDispatchCover($0, for: recipient.person) }
)
}
// MARK: - Last batch
private var lastBatchCard: some View {
let batch = model.dispatchLastBatch
let sent = batch.filter { $0.status == .mail }.count
let printed = batch.filter { $0.status == .pdf }.count
let failed = batch.filter { $0.status == .failed }.count
return SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .top) {
cardHeader(
icon: "clock.arrow.circlepath",
title: "Letzte Versendung",
subtitle: batch.first.map {
"\(Self.timestampFormatter.string(from: $0.createdAt)) · \(DayMath.key(batch.first?.rangeStart ?? model.range.start)) – \(DayMath.key(batch.first?.rangeEnd ?? model.range.end))"
} ?? "",
tint: LP.success
)
Spacer()
HStack(spacing: 6) {
if sent > 0 { TinyBadge(text: "\(sent) E-Mail", color: LP.accent) }
if printed > 0 { TinyBadge(text: "\(printed) Ausdruck", color: LP.burgundy) }
if failed > 0 { TinyBadge(text: "\(failed) fehlgeschlagen", color: LP.danger) }
}
}
logList(batch)
}
}
}
// MARK: - History
private var historyCard: some View {
SurfaceCard(padding: 17, radius: 15, background: LP.card) {
VStack(alignment: .leading, spacing: 10) {
cardHeader(
icon: "tray.full",
title: "Versendungsprotokoll",
subtitle: "Was für welchen Zeitraum an wen versendet wurde",
tint: LP.inkSecondary
)
ForEach(historyGroups) { group in
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 8) {
Text(Self.timestampFormatter.string(from: group.createdAt))
.font(.system(size: 10, weight: .semibold))
.foregroundStyle(LP.ink)
Text("\(DayMath.key(group.entries.first?.rangeStart ?? model.range.start)) – \(DayMath.key(group.entries.first?.rangeEnd ?? model.range.end))")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
Spacer()
Text("\(group.entries.count) \(group.entries.count == 1 ? "Empfänger" : "Empfänger")")
.font(.system(size: 9))
.foregroundStyle(LP.inkTertiary)
}
logList(group.entries)
}
.padding(.vertical, 6)
if group.id != historyGroups.last?.id {
Hairline()
}
}
}
}
}
private struct HistoryGroup: Identifiable {
var id: String { batchID }
var batchID: String
var createdAt: Date
var entries: [DispatchLogEntry]
}
private var historyGroups: [HistoryGroup] {
var order: [String] = []
var grouped: [String: [DispatchLogEntry]] = [:]
for entry in model.dispatchLog {
if grouped[entry.batchID] == nil {
order.append(entry.batchID)
}
grouped[entry.batchID, default: []].append(entry)
}
return order.prefix(12).compactMap { batchID in
guard let entries = grouped[batchID], let first = entries.first else { return nil }
return HistoryGroup(batchID: batchID, createdAt: first.createdAt, entries: entries)
}
}
private func logList(_ entries: [DispatchLogEntry]) -> some View {
VStack(spacing: 0) {
ForEach(entries) { entry in
HStack(spacing: 8) {
Image(systemName: entry.channel.symbolName)
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(entry.channel == .email ? LP.accent : LP.burgundy)
.frame(width: 16)
Text(entry.personName)
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink)
.frame(width: 150, alignment: .leading)
Text(entry.variant.shortTitle)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkSecondary)
.frame(width: 92, alignment: .leading)
if entry.channel == .print {
Text(entry.cover ? "mit Vorblatt" : "ohne Vorblatt")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.frame(width: 96, alignment: .leading)
} else {
Text(entry.email)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
.lineLimit(1)
.truncationMode(.middle)
.frame(width: 96, alignment: .leading)
}
Text(entry.status.title)
.font(.system(size: 9))
.foregroundStyle(statusColor(entry.status))
.lineLimit(1)
Spacer(minLength: 0)
}
.padding(.vertical, 3)
}
}
}
private func statusColor(_ status: DispatchStatus) -> Color {
switch status {
case .mail: LP.accent
case .pdf: LP.burgundy
case .failed: LP.danger
}
}
// MARK: - Shared
private func cardHeader(icon: String, title: String, subtitle: String, tint: Color) -> some View {
HStack(spacing: 9) {
Image(systemName: icon)
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(tint)
.frame(width: 28, height: 28)
.background(Circle().fill(tint.opacity(0.10)))
VStack(alignment: .leading, spacing: 1) {
Text(title)
.font(.system(size: 12.5, weight: .semibold))
.foregroundStyle(LP.ink)
Text(subtitle)
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
}
}
}
}