.ics Download und PDF Layout korrigiert

This commit is contained in:
concierge committed 2026-11-18 09:01:33 +01:00
1 parent dc20d7ec5a
commit cc2e85c111
11 files changed
+424 -73

No files matched your search

+83 -47
View File
@@ -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 {
+91
View File
@@ -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
+46
View File
@@ -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)
}
}
+78
View File
@@ -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{
+3
View File
@@ -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()
+1
View File
@@ -404,6 +404,7 @@ var iconPaths = map[string]string{
"send": `<path d="M22 2L11 13M22 2l-7 20-4-9-9-4z"/>`,
"mail": `<rect x="2" y="4" width="20" height="16" rx="2"/><path d="M3 6l9 7 9-7"/>`,
"copy": `<rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>`,
"download": `<path d="M12 3v12M7 10l5 5 5-5"/><path d="M5 21h14"/>`,
"plus": `<path d="M12 5v14M5 12h14"/>`,
"left": `<path d="M15 18l-6-6 6-6"/>`,
"right": `<path d="M9 18l6-6-6-6"/>`,
+1
View File
@@ -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))
+3 -2
View File
@@ -108,7 +108,7 @@
<th>Versandweg</th>
<th>Liste</th>
<th>Vorblatt</th>
<th>Text</th>
<th>Text / Kalender</th>
</tr>
</thead>
<tbody>
@@ -168,6 +168,7 @@
{{if and (not $.Data.SMTPConfigured) $person.Email}}
<a class="icon-button" href="{{.Mailto}}" data-mailto-link data-mailto-email="{{$person.Email}}" data-mail-assignments="{{.AssignmentText}}" title="Entwurf im eigenen E-Mail-Programm öffnen" aria-label="E-Mail an {{$person.FullName}} im E-Mail-Programm öffnen">{{icon "mail"}}</a>
{{end}}
<a class="icon-button" href="{{.CalendarURL}}" download title="Kalenderdatei (.ics) für {{$person.FullName}} herunterladen" aria-label="Kalenderdatei für {{$person.FullName}} herunterladen">{{icon "download"}}</a>
</td>
</tr>
{{else}}
@@ -176,7 +177,7 @@
</tbody>
</table>
</div>
<p class="table-note">E-Mail-Empfänger erhalten den Plan als PDF-Anhang und zusätzlich eine Kalenderdatei (.ics) mit ihren eigenen Einsätzen zum Import in gängige Kalender-Apps. Personen ohne Adresse oder mit der Auswahl „Ausdruck“ werden in einem sammelbaren PDF zusammengefasst – nacheinander mit Vorblatt und gewählter Liste. In der Spalte „Text“ kopiert das erste Symbol das persönliche Anschreiben; ohne SMTP öffnet das zweite Symbol einen fertigen Entwurf im eigenen E-Mail-Programm.{{if not .Data.CanManageSecrets}} Empfängeradressen und SMTP-Zugangsdaten sind für dieses Konto gesperrt und werden von Redakteuren verwaltet.{{end}}</p>
<p class="table-note">E-Mail-Empfänger erhalten den Plan als PDF-Anhang und zusätzlich eine Kalenderdatei (.ics) mit ihren eigenen Einsätzen zum Import in gängige Kalender-Apps. Ü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}}</p>
<div class="card-foot dispatch-actions">
<button class="btn btn-secondary" type="submit">{{icon "check"}} Auswahl speichern</button>
{{if .Data.SMTPConfigured}}