diff --git a/Sources/LektorenPlan/PDF/PlanPDFRenderer.swift b/Sources/LektorenPlan/PDF/PlanPDFRenderer.swift index 25c7a89..9cf4c88 100644 --- a/Sources/LektorenPlan/PDF/PlanPDFRenderer.swift +++ b/Sources/LektorenPlan/PDF/PlanPDFRenderer.swift @@ -63,6 +63,14 @@ enum PlanPDFRenderer { let churchWidth = (pageWidth - margin * 2 - dateWidth - liturgyWidth - columnGap * 5) / 4 let contentTop = margin + headerHeight + columnHeaderHeight + 4 let contentBottom = pageHeight - margin - footerHeight + let rowHeights = sortedRows.map { + rowHeight(row: $0, churchWidth: churchWidth, people: people) + } + let totalPages = paginationCount( + rowHeights: rowHeights, + contentTop: contentTop, + contentBottom: contentBottom + ) var pageIndex = 0 @@ -78,7 +86,7 @@ enum PlanPDFRenderer { } func endPage() { - drawFooter(pageIndex: pageIndex, range: range) + drawFooter(pageIndex: pageIndex, totalPages: totalPages, range: range) NSGraphicsContext.restoreGraphicsState() context.restoreGState() context.endPDFPage() @@ -92,11 +100,11 @@ enum PlanPDFRenderer { var cursorY = contentTop for (index, row) in sortedRows.enumerated() { - let height = rowHeight(row: row, churchWidth: churchWidth, people: people) + let height = rowHeights[index] if cursorY + height > contentBottom { endPage() beginPage() - drawHeader(range: range, generatedAt: generatedAt, continuation: true) + drawHeader(range: range, generatedAt: generatedAt) drawColumnHeader(churches: churches, churchWidth: churchWidth) cursorY = contentTop } @@ -137,7 +145,7 @@ enum PlanPDFRenderer { // MARK: - Page furniture - private static func drawHeader(range: DayRange, generatedAt: Date, continuation: Bool = false) { + private static func drawHeader(range: DayRange, generatedAt: Date) { let top = margin drawText( @@ -147,9 +155,9 @@ enum PlanPDFRenderer { color: accent ) drawText( - continuation ? "Gottesdienstplan · Fortsetzung" : "Gottesdienstplan", - in: CGRect(x: margin, y: top + 13, width: 500, height: 24), - font: serif(21, bold: true), + "Gottesdienstplan", + in: CGRect(x: margin, y: top + 13, width: 500, height: 22), + font: serif(17.5, bold: true), color: ink ) drawText( @@ -219,7 +227,7 @@ enum PlanPDFRenderer { contextLine(y: y + height) } - private static func drawFooter(pageIndex: Int, range: DayRange) { + private static func drawFooter(pageIndex: Int, totalPages: Int, range: DayRange) { let y = pageHeight - margin - footerHeight contextLine(y: y + 6) drawText( @@ -229,14 +237,31 @@ enum PlanPDFRenderer { color: tertiaryInk ) drawText( - "Seite \(pageIndex + 1)", - in: CGRect(x: pageWidth - margin - 90, y: y + 10, width: 90, height: 12), + "Seite \(pageIndex + 1) von \(max(totalPages, 1))", + in: CGRect(x: pageWidth - margin - 120, y: y + 10, width: 120, height: 12), font: sans(7), color: tertiaryInk, alignment: .right ) } + private static func paginationCount( + rowHeights: [CGFloat], + contentTop: CGFloat, + contentBottom: CGFloat + ) -> Int { + var pages = 1 + var cursor = contentTop + for height in rowHeights { + if cursor + height > contentBottom { + pages += 1 + cursor = contentTop + } + cursor += height + } + return pages + } + // MARK: - Rows private static func rowHeight( @@ -244,32 +269,59 @@ enum PlanPDFRenderer { churchWidth: CGFloat, people: [String: Person] ) -> CGFloat { - var tallest: CGFloat = 46 + let isSunday = row.liturgicalDay?.isSunday == true || DayMath.isSunday(row.date) + // Base height covers the date cell including the optional SONNTAG label. + var tallest: CGFloat = isSunday ? 52 : 42 if let day = row.liturgicalDay { - var liturgyHeight: CGFloat = 14 - liturgyHeight += measuredHeight(day.displayTitle, font: serif(10, bold: true), width: liturgyWidth - 8, maxLines: 3) + var liturgyHeight: CGFloat = 10 + let hasBadge = day.isHighFeast || day.rank == .feast || day.rank == .obligatoryMemorial + || (day.isObligation && !day.isSunday) + if hasBadge { liturgyHeight += 12 } + liturgyHeight += measuredHeight( + day.displayTitle, + font: serif(9.5, bold: day.isFeast), + width: liturgyWidth - 8, + maxLines: 3 + ) + liturgyHeight += 2 if !day.readings.isEmpty { - liturgyHeight += measuredHeight(day.readings.shortLabel, font: sans(7), width: liturgyWidth - 8, maxLines: 3) + 2 + liturgyHeight += measuredHeight( + day.readings.shortLabel, + font: sans(6.5), + width: liturgyWidth - 8, + maxLines: 3 + ) + 2 } - tallest = max(tallest, liturgyHeight + 8) + tallest = max(tallest, liturgyHeight + 4) } for church in row.services.map(\.church).uniqued(by: \.id) { let services = row.services.filter { $0.church.id == church.id } - var height: CGFloat = 5 + var height: CGFloat = 8 for service in services { - height += 12 + height += 11 if service.service.location != nil { height += 9 } for role in Role.allCases where service.service.requiredCount(for: role) > 0 { - height += 9 + let names = service.assignments(for: role).compactMap { people[$0.personID]?.fullName } + let prefix = role == .lector ? "L" : "K" + let value = names.isEmpty ? "offen" : names.joined(separator: ", ") + height += max( + 9, + measuredHeight( + "\(prefix): \(value)", + font: sans(6.5, weight: names.isEmpty ? .semibold : .regular), + width: churchWidth - 12, + maxLines: 2 + ) + ) } height += 3 } - tallest = max(tallest, height + 4) + tallest = max(tallest, height) } - return min(tallest, 150) + return tallest } private static func drawRow( @@ -389,14 +441,14 @@ enum PlanPDFRenderer { let names = service.assignments(for: role).compactMap { people[$0.personID]?.fullName } let prefix = role == .lector ? "L" : "K" let value = names.isEmpty ? "offen" : names.joined(separator: ", ") - drawText( + let roleHeight = drawText( "\(prefix): \(value)", in: CGRect(x: x + 7, y: serviceY, width: churchWidth - 12, height: 9), font: sans(6.5, weight: names.isEmpty ? .semibold : .regular), color: names.isEmpty ? openColor : secondaryInk, maxLines: 2 ) - serviceY += 9 + serviceY += max(9, roleHeight) } serviceY += 3 if serviceY > y + height - 6 { break } @@ -472,7 +524,9 @@ enum PlanPDFRenderer { width: CGFloat, maxLines: Int ) -> CGFloat { - let attributes: [NSAttributedString.Key: Any] = [.font: font] + let paragraph = NSMutableParagraphStyle() + paragraph.lineSpacing = 0.5 + let attributes: [NSAttributedString.Key: Any] = [.font: font, .paragraphStyle: paragraph] let measured = (text as NSString).boundingRect( with: CGSize(width: width, height: .greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], diff --git a/Sources/LektorenPlan/PlanModel.swift b/Sources/LektorenPlan/PlanModel.swift index 0a00371..ec75a43 100644 --- a/Sources/LektorenPlan/PlanModel.swift +++ b/Sources/LektorenPlan/PlanModel.swift @@ -1265,6 +1265,28 @@ final class PlanModel: ObservableObject { } } + /// Saves one recipient's personal calendar file via a save panel. The file + /// contains only that person's assignments, like the e-mail attachment. + func exportDispatchCalendar(for recipient: DispatchRecipient) { + let calendar = CalendarExport.ics( + calendarName: "Gottesdienstplan \(range.shortTitle)", + events: dispatchCalendarEvents(recipient.assignments) + ) + let panel = NSSavePanel() + panel.title = "Kalenderdatei sichern" + panel.nameFieldStringValue = dispatchCalendarFilename(for: recipient) + panel.allowedContentTypes = [UTType(filenameExtension: "ics") ?? .data] + panel.canCreateDirectories = true + guard panel.runModal() == .OK, let url = panel.url else { return } + do { + try Data(calendar.utf8).write(to: url, options: .atomic) + showToast("Kalenderdatei gespeichert: \(url.lastPathComponent)", kind: .success) + } catch { + alertTitle = "Kalenderdatei konnte nicht gespeichert werden" + alertMessage = error.localizedDescription + } + } + /// Builds one printable PDF: for each print recipient an optional cover /// sheet followed by the selected plan variant. func createDispatchPrintPDF() { diff --git a/Sources/LektorenPlan/Views/DispatchView.swift b/Sources/LektorenPlan/Views/DispatchView.swift index f12ed86..adf122d 100644 --- a/Sources/LektorenPlan/Views/DispatchView.swift +++ b/Sources/LektorenPlan/Views/DispatchView.swift @@ -212,7 +212,7 @@ struct DispatchView: View { Image(systemName: "info.circle") .font(.system(size: 10, weight: .semibold)) .foregroundStyle(LP.accent) - Text("Ohne hinterlegte E-Mail-Adresse wird automatisch gedruckt. E-Mails werden als Entwurf im Standard-Mailprogramm geöffnet – mit persönlichem Text, dem gewählten PDF und einer Kalenderdatei (.ics) mit den eigenen Einsätzen.") + Text("Ohne hinterlegte E-Mail-Adresse wird automatisch gedruckt. E-Mails werden als Entwurf im Standard-Mailprogramm geöffnet – mit persönlichem Text, dem gewählten PDF und einer Kalenderdatei (.ics) mit den eigenen Einsätzen. Über das Kalender-Symbol in der Empfängerzeile lässt sich die persönliche .ics-Datei auch einzeln sichern.") .font(.system(size: 9.5)) .foregroundStyle(LP.inkTertiary) .fixedSize(horizontal: false, vertical: true) @@ -283,6 +283,8 @@ struct DispatchView: View { .frame(width: 136, alignment: .leading) Text("VORBLATT") .frame(width: 66, alignment: .center) + Text("ICS") + .frame(width: 30, alignment: .center) } .font(.system(size: 8.5, weight: .bold, design: .rounded)) .tracking(0.7) @@ -351,6 +353,22 @@ struct DispatchView: View { .frame(width: 66) .disabled(recipient.effectiveChannel == .none) .help("Anschreiben als Vorblatt voranstellen") + + Button { + model.exportDispatchCalendar(for: recipient) + } label: { + Image(systemName: "calendar.badge.plus") + .font(.system(size: 11.5, weight: .semibold)) + .foregroundStyle(recipient.assignments.isEmpty ? LP.inkTertiary : LP.accent) + } + .buttonStyle(.plain) + .frame(width: 30) + .disabled(recipient.assignments.isEmpty) + .help( + recipient.assignments.isEmpty + ? "Keine Einsätze im Zeitraum" + : "Kalenderdatei (.ics) für \(recipient.person.fullName) sichern" + ) } .padding(.horizontal, 4) .padding(.vertical, 5) diff --git a/web/pdf/pdf.go b/web/pdf/pdf.go index 5620011..ec5147b 100644 --- a/web/pdf/pdf.go +++ b/web/pdf/pdf.go @@ -77,6 +77,9 @@ func newPDF(orientation string) *fpdf.Fpdf { pdf.SetCreator("LektorenPlan Web", true) pdf.SetTitle("LektorenPlan – Gottesdienstplan", true) pdf.SetMargins(8.5, 8.5, 8.5) + // The footer uses this alias for the total page count, which is only known + // when the document is closed. + pdf.AliasNbPages("{nb}") return pdf } @@ -288,20 +291,16 @@ func FullPlan(w io.Writer, r domain.DayRange, rows []domain.DayPlanRow, churches columns = columns[:4] } - drawHeader := func(continuation bool) { + drawHeader := func() { setColor(pdf, colors.accent) pdf.SetFont("Helvetica", "B", 6.4) pdf.SetXY(margin, margin) pdf.CellFormat(150, 3.4, tr("LEKTORENPLAN · "+strings.ToUpper(opts.tenant())), "", 0, "L", false, 0, "") setColor(pdf, colors.ink) - pdf.SetFont("Times", "B", 18) - title := "Gottesdienstplan" - if continuation { - title = "Gottesdienstplan · Fortsetzung" - } + pdf.SetFont("Times", "B", 15.5) pdf.SetXY(margin, margin+4.6) - pdf.CellFormat(150, 7, tr(title), "", 0, "L", false, 0, "") + pdf.CellFormat(150, 7, tr("Gottesdienstplan"), "", 0, "L", false, 0, "") setColor(pdf, colors.secondary) pdf.SetFont("Helvetica", "", 8.2) @@ -362,49 +361,16 @@ func FullPlan(w io.Writer, r domain.DayRange, rows []domain.DayPlanRow, churches pdf.SetFont("Helvetica", "", 5.8) pdf.SetXY(margin, y+2.6) pdf.CellFormat(150, 3, tr("LektorenPlan · "+r.ShortTitle()), "", 0, "L", false, 0, "") - pdf.SetXY(pageWidth-margin-30, y+2.6) - pdf.CellFormat(30, 3, tr(fmt.Sprintf("Seite %d", page)), "", 0, "R", false, 0, "") + pdf.SetXY(pageWidth-margin-45, y+2.6) + pdf.CellFormat(45, 3, tr(fmt.Sprintf("Seite %d von {nb}", page)), "", 0, "R", false, 0, "") } rowHeight := func(row domain.DayPlanRow) float64 { - height := 15.0 - if row.LiturgicalDay != nil { - titles := wrap(pdf, tr, row.LiturgicalDay.DisplayTitle(), liturgyW-4, 3) - readings := []string{} - if !row.LiturgicalDay.Readings.IsEmpty() { - readings = wrap(pdf, tr, row.LiturgicalDay.Readings.ShortLabel(), liturgyW-4, 3) - } - lit := 4.5 + float64(len(titles))*3.4 + float64(len(readings))*2.5 - if badge, _ := feastBadge(row.LiturgicalDay); badge != "" { - lit += 4.2 - } - if lit+2 > height { - height = lit + 2 - } - } - for _, service := range row.Services { - h := 5.0 - if service.Service.Location != nil && strings.TrimSpace(*service.Service.Location) != "" { - h += 3.2 - } - for _, role := range domain.AllRoles { - if service.Service.RequiredCount(role) > 0 { - h += 3.4 - } - } - h += 2.2 - if h > height { - height = h - } - } - if height > 53 { - height = 53 - } - return height + return fullPlanRowHeight(pdf, tr, row, churchWidth, peopleByID) } pdf.AddPage() - drawHeader(false) + drawHeader() drawColumnHeader() page := 1 y := contentTop @@ -422,7 +388,7 @@ func FullPlan(w io.Writer, r domain.DayRange, rows []domain.DayPlanRow, churches drawFooter(page) page++ pdf.AddPage() - drawHeader(true) + drawHeader() drawColumnHeader() y = contentTop } @@ -562,6 +528,76 @@ func FullPlan(w io.Writer, r domain.DayRange, rows []domain.DayPlanRow, churches return pdf.Error() } +// fullPlanRowHeight measures the space a day row actually needs. It mirrors the +// drawing code so a day with several services in one church grows instead of +// clipping the additional services. +func fullPlanRowHeight(pdf *fpdf.Fpdf, tr func(string) string, row domain.DayPlanRow, churchWidth float64, people map[string]domain.Person) float64 { + const liturgyWidth = 57.0 + // Base height covers the date cell including the optional SONNTAG label. + height := 15.0 + if row.IsSunday() { + height = 18.0 + } + if row.LiturgicalDay != nil { + style := "B" + if !row.LiturgicalDay.IsFeast() { + style = "" + } + pdf.SetFont("Times", style, 8.2) + titles := wrap(pdf, tr, row.LiturgicalDay.DisplayTitle(), liturgyWidth-4, 3) + lit := 1.6 + float64(len(titles))*3.3 + if badge, _ := feastBadge(row.LiturgicalDay); badge != "" { + lit += 4.2 + } + if !row.LiturgicalDay.Readings.IsEmpty() { + pdf.SetFont("Helvetica", "", 5.6) + readings := wrap(pdf, tr, row.LiturgicalDay.Readings.ShortLabel(), liturgyWidth-4, 3) + lit += 0.4 + float64(len(readings))*2.5 + } + lit += 2.0 + if lit > height { + height = lit + } + } + churchHeights := map[string]float64{} + var churchOrder []string + for _, service := range row.Services { + // 1.4 top padding + 3.4 service line + 1.5 gap below the service. + h := 6.3 + if service.Service.Location != nil && strings.TrimSpace(*service.Service.Location) != "" { + h += 3.0 + } + for _, role := range domain.AllRoles { + if service.Service.RequiredCount(role) <= 0 { + continue + } + prefix := "L: " + if role == domain.RoleHelper { + prefix = "K: " + } + names, open := namesFor(service, role, people) + weight := "" + if open > 0 { + weight = "B" + } + pdf.SetFont("Helvetica", weight, 5.4) + lines := wrap(pdf, tr, prefix+names, churchWidth-3, 2) + h += float64(len(lines)) * 3.0 + } + // Services in the same church column stack vertically. + if _, ok := churchHeights[service.Church.ID]; !ok { + churchOrder = append(churchOrder, service.Church.ID) + } + churchHeights[service.Church.ID] += h + } + for _, id := range churchOrder { + if churchHeights[id] > height { + height = churchHeights[id] + } + } + return height +} + // CompactPlan writes the A4 portrait service list. func CompactPlan(w io.Writer, r domain.DayRange, rows []domain.DayPlanRow, people []domain.Person, opts Options) error { pdf := newPDF("P") @@ -655,8 +691,8 @@ func CompactPlan(w io.Writer, r domain.DayRange, rows []domain.DayPlanRow, peopl pdf.SetFont("Helvetica", "", 5.8) pdf.SetXY(margin, y+2.6) pdf.CellFormat(150, 3, tr("LektorenPlan · kompakte Liste · "+r.ShortTitle()), "", 0, "L", false, 0, "") - pdf.SetXY(pageWidth-margin-25, y+2.6) - pdf.CellFormat(25, 3, tr(fmt.Sprintf("Seite %d", page)), "", 0, "R", false, 0, "") + pdf.SetXY(pageWidth-margin-45, y+2.6) + pdf.CellFormat(45, 3, tr(fmt.Sprintf("Seite %d von {nb}", page)), "", 0, "R", false, 0, "") } rowHeight := func(service domain.ServiceWithAssignments) float64 { diff --git a/web/pdf/pdf_test.go b/web/pdf/pdf_test.go index 87f67d4..8b3ef0a 100644 --- a/web/pdf/pdf_test.go +++ b/web/pdf/pdf_test.go @@ -3,7 +3,11 @@ package pdf import ( "bytes" "compress/zlib" + "fmt" "io" + "regexp" + "strconv" + "strings" "testing" "time" @@ -178,6 +182,93 @@ func TestFullPlan(t *testing.T) { } } +func multiPageRows() (domain.DayRange, []domain.DayPlanRow, []domain.Church, []domain.Person) { + _, _, churches, people := sampleRows() + church := churches[0] + person := people[0] + start := domain.MustDate("2026-01-01") + var rows []domain.DayPlanRow + for index := 0; index < 60; index++ { + date := domain.AddingDays(index, start) + var services []domain.ServiceWithAssignments + for slot := 0; slot < 3; slot++ { + id := fmt.Sprintf("s-%d-%d", index, slot) + services = append(services, domain.ServiceWithAssignments{ + Service: domain.ServiceOccurrence{ + ID: id, ChurchID: church.ID, Date: date, + TimeMinutes: 8*60 + slot, Title: "Hochamt", + LectorsNeeded: 1, HelpersNeeded: 1, + Kind: domain.KindRegular, CreatedAt: time.Now(), + }, + Church: church, + Assignments: []domain.Assignment{{ + ID: "a-" + id, ServiceID: id, PersonID: person.ID, + Role: domain.RoleLector, CreatedAt: time.Now(), + }}, + }) + } + rows = append(rows, domain.DayPlanRow{Date: date, Services: services}) + } + return domain.NewDayRange(start, rows[len(rows)-1].Date), rows, churches, people +} + +func TestFullPlanPaginatesWithTotalPageCount(t *testing.T) { + r, rows, churches, people := multiPageRows() + var buf bytes.Buffer + if err := FullPlan(&buf, r, rows, churches, people, Options{TenantName: "Bad Godesberg"}); err != nil { + t.Fatalf("render: %v", err) + } + content := string(pdfContentStreams(t, buf.Bytes())) + if strings.Contains(content, "Fortsetzung") { + t.Fatal("continuation title must not appear on later pages") + } + match := regexp.MustCompile(`Seite 1 von (\d+)`).FindStringSubmatch(content) + if match == nil { + t.Fatalf("first page footer is missing the total page count:\n%s", content) + } + total, err := strconv.Atoi(match[1]) + if err != nil || total < 2 { + t.Fatalf("total pages = %q, want at least 2", match[1]) + } + if !strings.Contains(content, fmt.Sprintf("Seite %d von %d", total, total)) { + t.Fatalf("last page footer is missing: want Seite %d von %d", total, total) + } + if got := strings.Count(content, "Seite "); got != total { + t.Fatalf("footer count = %d, want %d", got, total) + } +} + +func TestFullPlanRowHeightGrowsWithSeveralServices(t *testing.T) { + _, rows, _, people := sampleRows() + pdf := newPDF("L") + tr := translator(pdf) + peopleByID := map[string]domain.Person{} + for _, person := range people { + peopleByID[person.ID] = person + } + churchWidth := (297.0 - 8.5*2 - 17.0 - 57.0 - 1.35*5) / 4 + + row := rows[0] + oneService := fullPlanRowHeight(pdf, tr, row, churchWidth, peopleByID) + + base := row.Services[0] + for index := 0; index < 3; index++ { + extra := base + extra.Service.ID = fmt.Sprintf("extra-%d", index) + extra.Service.TimeMinutes = 11*60 + index + row.Services = append(row.Services, extra) + } + fourServices := fullPlanRowHeight(pdf, tr, row, churchWidth, peopleByID) + + if fourServices <= oneService { + t.Fatalf("row height did not grow: one service %.1f, four services %.1f", oneService, fourServices) + } + // A row must have room for all four service blocks, not a fixed cap. + if fourServices-oneService < 3*9 { + t.Fatalf("row height %.1f is too small for four services (one service %.1f)", fourServices, oneService) + } +} + func TestCompactPlan(t *testing.T) { r, rows, _, people := sampleRows() var buf bytes.Buffer diff --git a/web/web/dispatch_calendar_test.go b/web/web/dispatch_calendar_test.go index 92d0c00..ca8e1bc 100644 --- a/web/web/dispatch_calendar_test.go +++ b/web/web/dispatch_calendar_test.go @@ -1,6 +1,8 @@ package web import ( + "io" + "net/http" "strings" "testing" "time" @@ -62,3 +64,47 @@ func TestDispatchEmailBodyMentionsBothAttachments(t *testing.T) { t.Fatalf("draft body must not mention attachments:\n%s", draft) } } + +func TestDispatchCalendarDownload(t *testing.T) { + ts, _ := newTestServer(t) + client := newClient(t) + login(t, client, ts.URL, "editor", "editor123") + + resp, err := client.Get(ts.URL + "/dispatch/calendar?person=p-markus&start=2026-03-01&end=2026-03-31") + if err != nil { + t.Fatalf("GET calendar: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("calendar download = %d, want 200", resp.StatusCode) + } + if got := resp.Header.Get("Content-Type"); !strings.HasPrefix(got, "text/calendar") { + t.Fatalf("Content-Type = %q", got) + } + if got := resp.Header.Get("Content-Disposition"); !strings.Contains(got, ".ics") { + t.Fatalf("Content-Disposition = %q", got) + } + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read calendar: %v", err) + } + for _, want := range []string{"BEGIN:VCALENDAR", "VERSION:2.0", "END:VCALENDAR"} { + if !strings.Contains(string(body), want) { + t.Fatalf("calendar misses %q:\n%s", want, body) + } + } +} + +func TestDispatchCalendarRequiresEditor(t *testing.T) { + ts, _ := newTestServer(t) + reader := newClient(t) + login(t, reader, ts.URL, "reader", "reader123") + resp, err := reader.Get(ts.URL + "/dispatch/calendar?person=p-markus&start=2026-03-01&end=2026-03-31") + if err != nil { + t.Fatalf("GET calendar: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + t.Fatalf("reader calendar download = %d, want 403", resp.StatusCode) + } +} diff --git a/web/web/dispatch_handlers.go b/web/web/dispatch_handlers.go index 45b9fde..7f5b4b1 100644 --- a/web/web/dispatch_handlers.go +++ b/web/web/dispatch_handlers.go @@ -68,6 +68,7 @@ type dispatchPersonView struct { AssignmentText string MailText string Mailto string + CalendarURL string } type dispatchPageData struct { @@ -262,6 +263,12 @@ func dispatchCalendarEvents(assignments []dispatchAssignmentView) []domain.Calen return events } +// dispatchCalendarURL builds the download link for one recipient's calendar. +func dispatchCalendarURL(personID string, rng domain.DayRange) string { + return "/dispatch/calendar?person=" + url.QueryEscape(personID) + + "&start=" + domain.Key(rng.Start) + "&end=" + domain.Key(rng.End) +} + func (s *Server) dispatchPeople(ctx context.Context, tenantID string, rows []domain.DayPlanRow) ([]dispatchPersonView, error) { people, err := s.store.People(ctx, tenantID) if err != nil { @@ -325,6 +332,7 @@ func (s *Server) handleDispatch(w http.ResponseWriter, r *http.Request, user *st for index := range people { people[index].AssignmentText = emailAssignmentTable(people[index].Assignments) people[index].MailText = dispatchEmailBody(intro, greeting, rng, people[index].Assignments, false) + people[index].CalendarURL = dispatchCalendarURL(people[index].Person.ID, rng) if email := strings.TrimSpace(people[index].Person.Email); email != "" { people[index].Mailto = dispatchMailto(email, subject, people[index].MailText) } @@ -379,6 +387,76 @@ func (s *Server) handleDispatch(w http.ResponseWriter, r *http.Request, user *st s.renderPage(w, r, "dispatch", data) } +// handleDispatchCalendar downloads one recipient's calendar file. Like the +// e-mail attachment it only contains that person's own assignments. +func (s *Server) handleDispatchCalendar(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) { + if tenant == nil { + s.redirect(w, r, "/plan") + return + } + rng := s.rangeFromRequest(r) + personID := strings.TrimSpace(r.URL.Query().Get("person")) + if personID == "" { + s.setFlash(w, "Für den Kalender-Download fehlt die Person.", "error") + s.redirect(w, r, "/dispatch?start="+domain.Key(rng.Start)+"&end="+domain.Key(rng.End)) + return + } + people, err := s.store.People(r.Context(), tenant.ID) + if err != nil { + s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error()) + return + } + var person domain.Person + found := false + for _, candidate := range people { + if candidate.ID == personID { + person = candidate + found = true + break + } + } + if !found { + s.renderError(w, r, http.StatusNotFound, "Versendung", "Die Person wurde nicht gefunden.") + return + } + rows, err := s.store.PlanRows(r.Context(), tenant.ID, rng) + if err != nil { + s.renderError(w, r, http.StatusInternalServerError, "Versendung", err.Error()) + return + } + assignments := dispatchAssignments(rows, person.ID) + calendar := domain.CalendarICS("Gottesdienstplan "+tenant.Name, dispatchCalendarEvents(assignments)) + prefix := tenant.Slug + if component := dispatchFilenameComponent(person.LastName); component != "" { + prefix += "-" + component + } + name := domain.CalendarFilename(prefix, domain.Key(rng.Start)) + w.Header().Set("Content-Type", "text/calendar; charset=utf-8") + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name)) + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Length", strconv.Itoa(len(calendar))) + _, _ = w.Write([]byte(calendar)) +} + +// dispatchFilenameComponent keeps download names ASCII and filesystem-safe. +func dispatchFilenameComponent(value string) string { + replacer := strings.NewReplacer( + "ä", "ae", "ö", "oe", "ü", "ue", + "Ä", "Ae", "Ö", "Oe", "Ü", "Ue", "ß", "ss", + ) + value = replacer.Replace(strings.TrimSpace(value)) + var builder strings.Builder + for _, r := range value { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_': + builder.WriteRune(r) + case r == ' ' || r == '.' || r == ',': + builder.WriteRune('-') + } + } + return strings.Trim(builder.String(), "-") +} + func (s *Server) dispatchFormFromRequest(r *http.Request, people []domain.Person) dispatchForm { rng := formRange(r) form := dispatchForm{ diff --git a/web/web/dispatch_test.go b/web/web/dispatch_test.go index 5070846..370152c 100644 --- a/web/web/dispatch_test.go +++ b/web/web/dispatch_test.go @@ -32,6 +32,9 @@ func TestDispatchPageAndPreferences(t *testing.T) { if !strings.Contains(body, "Versendung") { t.Fatal("dispatch page is missing its heading") } + if !strings.Contains(body, "/dispatch/calendar?person=") { + t.Fatal("dispatch page is missing the calendar download links") + } csrf := extractCSRF(t, body) ctx := context.Background() diff --git a/web/web/render.go b/web/web/render.go index b7f2e8b..d73ed7b 100644 --- a/web/web/render.go +++ b/web/web/render.go @@ -404,6 +404,7 @@ var iconPaths = map[string]string{ "send": ``, "mail": ``, "copy": ``, + "download": ``, "plus": ``, "left": ``, "right": ``, diff --git a/web/web/server.go b/web/web/server.go index 2b8c336..fbba04a 100644 --- a/web/web/server.go +++ b/web/web/server.go @@ -183,6 +183,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /pdf", s.auth(s.handlePDF)) mux.HandleFunc("GET /dispatch", s.editor(s.handleDispatch)) + mux.HandleFunc("GET /dispatch/calendar", s.editor(s.handleDispatchCalendar)) 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)) diff --git a/web/web/templates/dispatch.html b/web/web/templates/dispatch.html index c8884ca..fed1d39 100644 --- a/web/web/templates/dispatch.html +++ b/web/web/templates/dispatch.html @@ -108,7 +108,7 @@ Versandweg Liste Vorblatt - Text + Text / Kalender @@ -168,6 +168,7 @@ {{if and (not $.Data.SMTPConfigured) $person.Email}} {{icon "mail"}} {{end}} + {{icon "download"}} {{else}} @@ -176,7 +177,7 @@ -

E-Mail-Empfänger erhalten den Plan als PDF-Anhang und zusätzlich eine Kalenderdatei (.ics) mit ihren eigenen Einsätzen zum Import in gängige Kalender-Apps. Personen ohne Adresse oder mit der Auswahl „Ausdruck“ werden in einem sammelbaren PDF zusammengefasst – nacheinander mit Vorblatt und gewählter Liste. In der Spalte „Text“ kopiert das erste Symbol das persönliche Anschreiben; ohne SMTP öffnet das zweite Symbol einen fertigen Entwurf im eigenen E-Mail-Programm.{{if not .Data.CanManageSecrets}} Empfängeradressen und SMTP-Zugangsdaten sind für dieses Konto gesperrt und werden von Redakteuren verwaltet.{{end}}

+

E-Mail-Empfänger erhalten den Plan als PDF-Anhang und zusätzlich eine Kalenderdatei (.ics) mit ihren eigenen Einsätzen zum Import in gängige Kalender-Apps. Über das Kalender-Symbol in der Spalte „Text / Kalender“ lässt sich die persönliche .ics-Datei auch einzeln herunterladen. Personen ohne Adresse oder mit der Auswahl „Ausdruck“ werden in einem sammelbaren PDF zusammengefasst – nacheinander mit Vorblatt und gewählter Liste. In der Spalte „Text“ kopiert das erste Symbol das persönliche Anschreiben; ohne SMTP öffnet das zweite Symbol einen fertigen Entwurf im eigenen E-Mail-Programm.{{if not .Data.CanManageSecrets}} Empfängeradressen und SMTP-Zugangsdaten sind für dieses Konto gesperrt und werden von Redakteuren verwaltet.{{end}}

{{if .Data.SMTPConfigured}}