package pdf import ( "bytes" "compress/zlib" "fmt" "io" "regexp" "strconv" "strings" "testing" "time" "lektorenplan/domain" ) func sampleRows() (domain.DayRange, []domain.DayPlanRow, []domain.Church, []domain.Person) { church := domain.Church{ID: "c1", Name: "St. Andreas", ShortName: "Andreas", Symbol: domain.SymbolBasilica, ColorHex: "#9B5B44", Address: "Andreasstraße 1", SortIndex: 0} person := domain.Person{ID: "p1", FirstName: "Anna", LastName: "Berg", Roles: []domain.Role{domain.RoleLector}, Active: true} service := domain.ServiceOccurrence{ ID: "s1", ChurchID: "c1", Date: domain.MustDate("2026-11-15"), TimeMinutes: 9*60 + 30, Title: "Hochamt", LectorsNeeded: 1, HelpersNeeded: 2, Kind: domain.KindRegular, CreatedAt: time.Now(), } assignment := domain.Assignment{ID: "a1", ServiceID: "s1", PersonID: "p1", Role: domain.RoleLector} liturgy := domain.LiturgicalDay{ Date: domain.MustDate("2026-11-15"), Title: "33. Sonntag im Jahreskreis", Rank: domain.RankSolemnity, Color: domain.ColorGreen, Readings: domain.Readings{First: "Mal 3, 19-20a", Gospel: "Lk 21, 5-19"}, IsObligation: true, Source: "test", } row := domain.DayPlanRow{ Date: domain.MustDate("2026-11-15"), LiturgicalDay: &liturgy, Services: []domain.ServiceWithAssignments{{Service: service, Church: church, Assignments: []domain.Assignment{assignment}}}, } r := domain.NewDayRange(domain.MustDate("2026-11-15"), domain.MustDate("2026-11-15")) return r, []domain.DayPlanRow{row}, []domain.Church{church}, []domain.Person{person} } func umlautRows() (domain.DayRange, []domain.DayPlanRow, []domain.Church, []domain.Person) { location := "Mariä-Himmelfahrt-Kapelle" church := domain.Church{ID: "c1", Name: "St. Mariä Himmelfahrt", ShortName: "Mariä", Symbol: domain.SymbolBasilica, ColorHex: "#9B5B44", Address: "Andreasstraße 1", SortIndex: 0} person := domain.Person{ID: "p1", FirstName: "Jürgen", LastName: "Müller", Roles: []domain.Role{domain.RoleLector}, Active: true} service := domain.ServiceOccurrence{ ID: "s1", ChurchID: "c1", Date: domain.MustDate("2026-11-15"), TimeMinutes: 9*60 + 30, Title: "Hochamt für die Gemeinde", Location: &location, LectorsNeeded: 1, HelpersNeeded: 1, Kind: domain.KindRegular, CreatedAt: time.Now(), } assignment := domain.Assignment{ID: "a1", ServiceID: "s1", PersonID: "p1", Role: domain.RoleLector} liturgy := domain.LiturgicalDay{ Date: domain.MustDate("2026-11-15"), Title: "Hochfest Mariä Himmelfahrt", Rank: domain.RankSolemnity, Color: domain.ColorWhite, Readings: domain.Readings{First: "Jes 61, 9a.10b", Gospel: "Lk 1, 39-56"}, IsObligation: true, Source: "test", } row := domain.DayPlanRow{ Date: domain.MustDate("2026-11-15"), LiturgicalDay: &liturgy, Services: []domain.ServiceWithAssignments{{Service: service, Church: church, Assignments: []domain.Assignment{assignment}}}, } r := domain.NewDayRange(domain.MustDate("2026-11-15"), domain.MustDate("2026-11-15")) return r, []domain.DayPlanRow{row}, []domain.Church{church}, []domain.Person{person} } // pdfContentStreams returns the decoded page content streams of a PDF. Text // written with core fonts is stored there as single-byte cp1252 strings. func pdfContentStreams(t *testing.T, data []byte) []byte { t.Helper() var out bytes.Buffer for { open := bytes.Index(data, []byte("stream")) if open < 0 { break } start := open + len("stream") if start < len(data) && data[start] == '\r' { start++ } if start < len(data) && data[start] == '\n' { start++ } end := bytes.Index(data[start:], []byte("endstream")) if end < 0 { break } raw := bytes.TrimRight(data[start:start+end], "\r\n") if reader, err := zlib.NewReader(bytes.NewReader(raw)); err == nil { decoded, err := io.ReadAll(reader) reader.Close() if err == nil { out.Write(decoded) out.WriteByte('\n') } } else { out.Write(raw) out.WriteByte('\n') } data = data[start+end+len("endstream"):] } if out.Len() == 0 { t.Fatal("no content streams found in PDF") } return out.Bytes() } func TestPDFUmlautsAreEncoded(t *testing.T) { r, rows, churches, people := umlautRows() person := people[0] cover := CoverData{ TenantName: "Köln", Diocese: "Erzbistum Köln", Range: r, Person: person, Intro: "Grüße aus dem Pfarrbüro.", Greeting: "Herzliche Grüße", Assignments: []DispatchAssignment{{ Date: domain.MustDate("2026-11-15"), TimeMinutes: 9*60 + 30, Church: "St. Mariä Himmelfahrt", Title: "Hochamt für die Gemeinde", RoleLabel: "Lektor", }}, GeneratedAt: time.Now(), } documents := []struct { name string render func(io.Writer) error present []string }{ { name: "full", render: func(w io.Writer) error { return FullPlan(w, r, rows, churches, people, Options{TenantName: "Köln", Diocese: "Erzbistum Köln"}) }, present: []string{"K\xf6ln", "M\xfcller", "Andreasstra\xdfe", "Mari\xe4", "f\xfcr"}, }, { name: "compact", render: func(w io.Writer) error { return CompactPlan(w, r, rows, people, Options{TenantName: "Köln", Diocese: "Erzbistum Köln"}) }, present: []string{"K\xd6LN", "M\xfcller", "Mari\xe4", "f\xfcr"}, }, { name: "cover", render: func(w io.Writer) error { return Cover(w, cover) }, present: []string{ "K\xf6ln", "M\xfcller", "Mari\xe4", "f\xfcr", "Gr\xfc\xdfe", }, }, } for _, document := range documents { t.Run(document.name, func(t *testing.T) { var buf bytes.Buffer if err := document.render(&buf); err != nil { t.Fatalf("render: %v", err) } content := pdfContentStreams(t, buf.Bytes()) for _, want := range document.present { if !bytes.Contains(content, []byte(want)) { t.Errorf("cp1252 sequence %q missing from PDF content", want) } } for _, raw := range []string{ "K\xc3\xb6ln", "M\xc3\xbcller", "Andreasstra\xc3\x9fe", "Mari\xc3\xa4", "f\xc3\xbcr", "Gr\xc3\xbc\xc3\x9fe", } { if bytes.Contains(content, []byte(raw)) { t.Errorf("raw UTF-8 sequence %q found in PDF content", raw) } } }) } } func TestFullPlan(t *testing.T) { r, rows, churches, people := sampleRows() var buf bytes.Buffer if err := FullPlan(&buf, r, rows, churches, people, Options{TenantName: "Bad Godesberg"}); err != nil { t.Fatalf("render: %v", err) } if buf.Len() < 1000 || !bytes.HasPrefix(buf.Bytes(), []byte("%PDF")) { t.Fatalf("unexpected PDF output (%d bytes)", buf.Len()) } } 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") } if got := strings.Count(content, "Gottesdienstplan"); got != 1 { t.Fatalf("large title appears %d times, want only on the first page", got) } 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 if err := CompactPlan(&buf, r, rows, people, Options{TenantName: "Bad Godesberg"}); err != nil { t.Fatalf("render: %v", err) } if buf.Len() < 1000 || !bytes.HasPrefix(buf.Bytes(), []byte("%PDF")) { t.Fatalf("unexpected PDF output (%d bytes)", buf.Len()) } } func TestCompactPlanPaginatesWithoutContinuationTitle(t *testing.T) { r, rows, _, people := multiPageRows() var buf bytes.Buffer if err := CompactPlan(&buf, r, rows, 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") } if strings.Contains(content, "A4 hoch") { t.Fatal("paper hint must not appear in the compact header") } 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) } } // A cover sheet placed between plan pages used to be overwritten by the next // document's imported templates, so its letter text disappeared from the // dispatch packet. func TestMergeKeepsCoverBetweenPlanDocuments(t *testing.T) { r, rows, _, people := sampleRows() var cover bytes.Buffer if err := Cover(&cover, CoverData{ TenantName: "Köln", Diocese: "Erzbistum Köln", Range: r, Person: people[0], Intro: "Liebe Lektorinnen und Lektoren, liebe Kommunionhelferinnen und -helfer,", Greeting: "Mit freundlichen Grüßen", GeneratedAt: time.Now(), }); err != nil { t.Fatalf("cover: %v", err) } var plan bytes.Buffer if err := CompactPlan(&plan, r, rows, people, Options{TenantName: "Köln"}); err != nil { t.Fatalf("plan: %v", err) } merged, err := Merge([][]byte{plan.Bytes(), cover.Bytes(), plan.Bytes()}) if err != nil { t.Fatalf("merge: %v", err) } content := string(pdfContentStreams(t, merged)) if !strings.Contains(content, "Liebe Lektorinnen") { t.Fatal("cover letter text is missing from the merged packet") } if !strings.Contains(content, "Gottesdienstliste") { t.Fatal("plan text is missing from the merged packet") } pages, err := documentPages(merged) if err != nil { t.Fatalf("page sizes: %v", err) } if len(pages) != 3 { t.Fatalf("merged page count = %d, want 3", len(pages)) } for _, page := range pages { if page.width < 200 || page.width > 220 || page.height < 285 || page.height > 305 { t.Fatalf("page size = %.1f x %.1f mm, want A4 portrait", page.width, page.height) } } } func TestPadToEvenPages(t *testing.T) { r, _, _, people := sampleRows() var cover bytes.Buffer if err := Cover(&cover, CoverData{ TenantName: "Köln", Range: r, Person: people[0], Intro: "Ein kurzer Text.", GeneratedAt: time.Now(), }); err != nil { t.Fatalf("cover: %v", err) } if count, err := PageCount(cover.Bytes()); err != nil || count != 1 { t.Fatalf("cover page count = %d, %v; want 1", count, err) } padded, err := PadToEvenPages(cover.Bytes()) if err != nil { t.Fatalf("pad cover: %v", err) } if count, err := PageCount(padded); err != nil || count != 2 { t.Fatalf("padded cover page count = %d, %v; want 2", count, err) } even, err := Merge([][]byte{cover.Bytes(), cover.Bytes()}) if err != nil { t.Fatalf("merge even document: %v", err) } unchanged, err := PadToEvenPages(even) if err != nil { t.Fatalf("pad even document: %v", err) } if !bytes.Equal(unchanged, even) { t.Fatal("a document with an even page count must not be changed") } r, rows, churches, people := sampleRows() var landscape bytes.Buffer if err := FullPlan(&landscape, r, rows, churches, people, Options{TenantName: "Köln"}); err != nil { t.Fatalf("full plan: %v", err) } padded, err = PadToEvenPages(landscape.Bytes()) if err != nil { t.Fatalf("pad full plan: %v", err) } pages, err := documentPages(padded) if err != nil { t.Fatalf("page sizes: %v", err) } if len(pages) != 2 { t.Fatalf("padded full plan page count = %d, want 2", len(pages)) } for _, page := range pages { if page.width < 285 || page.width > 305 || page.height < 200 || page.height > 220 { t.Fatalf("page size = %.1f x %.1f mm, want A4 landscape", page.width, page.height) } } } // The address block already names the recipient. The cover must not repeat the // name in parentheses at the end. func TestCoverNamesRecipientOnlyInAddressBlock(t *testing.T) { r, _, _, people := sampleRows() var buf bytes.Buffer if err := Cover(&buf, CoverData{ TenantName: "Köln", Range: r, Person: people[0], Intro: "Ein kurzer Text.", Greeting: "Mit freundlichen Grüßen", GeneratedAt: time.Now(), }); err != nil { t.Fatalf("cover: %v", err) } content := string(pdfContentStreams(t, buf.Bytes())) if count := strings.Count(content, "Anna Berg"); count != 1 { t.Fatalf("recipient name appears %d times, want only the address block:\n%s", count, content) } if strings.Contains(content, "\\(Anna Berg\\)") { t.Fatalf("cover must not repeat the recipient in parentheses:\n%s", content) } } // A dispatch packet mixes the portrait cover with the optional landscape plan. // Passing landscape dimensions together with fpdf's "L" orientation used to // swap them back to portrait and crop the plan. func TestMergeKeepsPortraitAndLandscapePages(t *testing.T) { r, rows, churches, people := sampleRows() var cover bytes.Buffer if err := Cover(&cover, CoverData{ TenantName: "Köln", Range: r, Person: people[0], Intro: "Ein kurzer Text.", GeneratedAt: time.Now(), }); err != nil { t.Fatalf("cover: %v", err) } var plan bytes.Buffer if err := FullPlan(&plan, r, rows, churches, people, Options{TenantName: "Köln"}); err != nil { t.Fatalf("full plan: %v", err) } merged, err := Merge([][]byte{cover.Bytes(), plan.Bytes()}) if err != nil { t.Fatalf("merge: %v", err) } pages, err := documentPages(merged) if err != nil { t.Fatalf("page sizes: %v", err) } if len(pages) != 2 { t.Fatalf("merged page count = %d, want 2", len(pages)) } if pages[0].width >= pages[0].height { t.Fatalf("cover page is not portrait: %.1f x %.1f mm", pages[0].width, pages[0].height) } if pages[1].width <= pages[1].height { t.Fatalf("plan page is not landscape: %.1f x %.1f mm", pages[1].width, pages[1].height) } } // The cover sheet must render the same letter text as the e-mail. A long // introduction used to run past the page because the cover is laid out with // explicit coordinates and page breaking was disabled. func TestCoverKeepsCompleteLetterText(t *testing.T) { r, _, _, people := sampleRows() firstParagraph := "Liebe Lektorinnen und Lektoren, liebe Kommunionhelferinnen und -helfer," lastParagraph := "Der Schluss des langen Freitextes bleibt sichtbar." longMiddle := strings.Repeat("Dieser Satz füllt das Vorblatt über mehrere Seiten hinweg. ", 90) greeting := "Mit freundlichen Grüßen\nIhr Pfarreiteam" var buf bytes.Buffer if err := Cover(&buf, CoverData{ TenantName: "Köln", Range: r, Person: people[0], Intro: firstParagraph + "\n\n" + longMiddle + "\n\n" + lastParagraph, Greeting: greeting, GeneratedAt: time.Now(), }); err != nil { t.Fatalf("cover: %v", err) } content := string(pdfContentStreams(t, buf.Bytes())) for _, want := range []string{firstParagraph, lastParagraph, "Mit freundlichen"} { if !strings.Contains(content, want) { t.Fatalf("cover is missing %q:\n%s", want, content) } } if pages, err := PageCount(buf.Bytes()); err != nil || pages < 2 { t.Fatalf("long cover text should span several pages, got %d (%v)", pages, err) } }