Add email verification, personal calendar feed, and full SEO implementation

- Customer accounts now require email verification (hashed, single-use,
  time-limited tokens) before they can request/confirm bookings, with
  resend flows on login/account/booking widget and rate limiting.
- Admins get a private, rotatable iCalendar (ICS) subscription feed of
  their confirmed bookings and public events, timezone-correct for
  Europe/Berlin including DST, never exposing meeting passwords.
- Adds a full SEO layer: per-page canonical/OG/Twitter metadata with
  CMS-editable overrides and content-derived fallbacks, a dynamic
  sitemap.xml and robots.txt driven by real published content, JSON-LD
  (Organization/LocalBusiness, WebSite, WebPage, BreadcrumbList, Service,
  Event, BlogPosting) that never fabricates data, and a CMS-managed
  redirect table for changed slugs.
- Global ANOUMA-naming audit: the brand name is never used to label
  personal account/calendar areas anywhere in the app, CMS, or emails.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-25 22:57:31 +02:00
co-authored by Claude Sonnet 5
parent 50c39a70e0
commit 1cd15aff25
72 changed files with 2835 additions and 257 deletions
+36
View File
@@ -0,0 +1,36 @@
import { getSEOSettingsGlobal } from "@/lib/payload/globals";
import { siteConfig } from "@/lib/site";
function stripTrailingSlash(url: string): string {
return url.replace(/\/+$/, "");
}
/**
* The canonical base URL for the whole site. Prefers the CMS override
* (SEO-Einstellungen → Website-URL) when it's a valid absolute URL, then
* NEXT_PUBLIC_SERVER_URL (the single source of truth used everywhere else
* in this app — emails, meeting links, Payload's own serverURL), then the
* hardcoded siteConfig fallback. Never throws — SEO metadata must never
* break a page render.
*/
export async function getSiteUrl(): Promise<string> {
try {
const settings = await getSEOSettingsGlobal();
if (settings.siteUrl && /^https?:\/\/.+/.test(settings.siteUrl)) {
return stripTrailingSlash(settings.siteUrl);
}
} catch {
// CMS/DB unreachable — fall through to the env-based default.
}
return stripTrailingSlash(process.env.NEXT_PUBLIC_SERVER_URL || siteConfig.domain);
}
/** Whether the site should be indexable at all (global kill switch in the CMS). */
export async function isSiteIndexable(): Promise<boolean> {
try {
const settings = await getSEOSettingsGlobal();
return settings.robotsIndexable !== false;
} catch {
return true;
}
}
+29
View File
@@ -0,0 +1,29 @@
/**
* Formats a JS Date as an ISO 8601 string carrying its actual Europe/Berlin
* UTC offset (e.g. "2026-06-15T09:00:00+02:00" in summer,
* "...+01:00" in winter) — what schema.org's Event startDate/endDate
* expect. Uses Intl's timezone database rather than hardcoded +1/+2 math,
* so it's correct across the DST transition automatically.
*/
export function toBerlinOffsetISOString(date: Date): string {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: "Europe/Berlin",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hourCycle: "h23",
timeZoneName: "shortOffset",
}).formatToParts(date);
const get = (type: string) => parts.find((p) => p.type === type)?.value ?? "00";
const tzName = parts.find((p) => p.type === "timeZoneName")?.value ?? "GMT+0";
const match = /GMT([+-])(\d+)(?::(\d+))?/.exec(tzName);
const sign = match?.[1] ?? "+";
const offsetHours = (match?.[2] ?? "0").padStart(2, "0");
const offsetMinutes = (match?.[3] ?? "0").padStart(2, "0");
return `${get("year")}-${get("month")}-${get("day")}T${get("hour")}:${get("minute")}:${get("second")}${sign}${offsetHours}:${offsetMinutes}`;
}
+231
View File
@@ -0,0 +1,231 @@
import { siteConfig } from "@/lib/site";
import { toBerlinOffsetISOString } from "./dates";
import type { BookingSetting, Contact, Event, Offer, Post, SeoSetting } from "@/payload-types";
// Server-only builders — every function here returns `null` instead of
// guessing when the real data needed for a valid/honest result isn't
// present. Nothing here ever invents a review, price, address or phone
// number (see section 27/35 of the SEO brief).
/** JSON.stringify with `<` escaped so this can never be broken out of by any (currently non-existent) embedded "</script>" sequence. */
function toSafeJsonLdString(data: unknown): string {
return JSON.stringify(data).replace(/</g, "\\u003c");
}
type JsonLdValue = Record<string, unknown>;
export function organizationName(settings: SeoSetting | null | undefined): string {
return settings?.businessName?.trim() || siteConfig.name;
}
function hasFullAddress(booking: BookingSetting | null | undefined): booking is BookingSetting & { street: string; city: string; postalCode: string } {
return Boolean(booking?.street?.trim() && booking?.city?.trim() && booking?.postalCode?.trim());
}
function postalAddress(booking: BookingSetting) {
return {
"@type": "PostalAddress",
streetAddress: booking.street!.trim(),
postalCode: booking.postalCode!.trim(),
addressLocality: booking.city!.trim(),
...(booking.region?.trim() ? { addressRegion: booking.region.trim() } : {}),
...(booking.country?.trim() ? { addressCountry: booking.country.trim() } : {}),
};
}
/**
* Organization (always safe — just a name and a URL) upgraded to
* ProfessionalService/LocalBusiness once a real, complete street address
* has actually been entered in the CMS. Phone/opening hours/geo are added
* only when present; nothing is fabricated to "complete" the schema.
*/
export function organizationOrLocalBusinessJsonLd(args: {
settings: SeoSetting | null | undefined;
booking: BookingSetting | null | undefined;
contact: Contact | null | undefined;
siteUrl: string;
}): JsonLdValue {
const name = organizationName(args.settings);
const base: JsonLdValue = {
"@context": "https://schema.org",
name,
url: args.siteUrl,
};
if (args.settings?.businessDescription?.trim()) base.description = args.settings.businessDescription.trim();
if (args.contact?.email) base.email = args.contact.email;
if (!hasFullAddress(args.booking)) {
return { ...base, "@type": "Organization" };
}
const result: JsonLdValue = {
...base,
"@type": "ProfessionalService",
address: postalAddress(args.booking),
};
if (args.contact?.phone?.trim()) result.telephone = args.contact.phone.trim();
if (typeof args.settings?.latitude === "number" && typeof args.settings?.longitude === "number") {
result.geo = { "@type": "GeoCoordinates", latitude: args.settings.latitude, longitude: args.settings.longitude };
}
if (args.settings?.openingHours?.length) {
result.openingHoursSpecification = args.settings.openingHours.map((entry) => ({
"@type": "OpeningHoursSpecification",
dayOfWeek: entry.days.map((day) => `https://schema.org/${day}`),
opens: entry.opens,
closes: entry.closes,
}));
}
if (args.settings?.socialLinks?.length) {
result.sameAs = args.settings.socialLinks.map((link) => link.url).filter(Boolean);
}
return result;
}
export function websiteJsonLd(siteUrl: string): JsonLdValue {
return {
"@context": "https://schema.org",
"@type": "WebSite",
name: siteConfig.name,
url: siteUrl,
};
}
export function webPageJsonLd(args: { name: string; description: string; url: string }): JsonLdValue {
return {
"@context": "https://schema.org",
"@type": "WebPage",
name: args.name,
description: args.description,
url: args.url,
};
}
export function breadcrumbJsonLd(items: { name: string; url?: string }[]): JsonLdValue | null {
if (items.length === 0) return null;
return {
"@context": "https://schema.org",
"@type": "BreadcrumbList",
// The last item's "item" URL is deliberately omitted when absent —
// that's the current page, and per Google's guidelines a BreadcrumbList
// entry doesn't need a URL for the page the visitor is already on.
itemListElement: items.map((item, index) => ({
"@type": "ListItem",
position: index + 1,
name: item.name,
...(item.url ? { item: item.url } : {}),
})),
};
}
export function serviceJsonLd(args: {
offer: Offer;
description: string;
imageUrl?: string;
siteUrl: string;
providerName: string;
areaServed?: string;
}): JsonLdValue {
const result: JsonLdValue = {
"@context": "https://schema.org",
"@type": "Service",
name: args.offer.title,
description: args.description,
url: `${args.siteUrl}/angebote/${args.offer.slug}`,
provider: { "@type": "Organization", name: args.providerName, url: args.siteUrl },
};
if (args.imageUrl) result.image = args.imageUrl;
if (args.areaServed) result.areaServed = args.areaServed;
// Deliberately no "offers"/price — the CMS "price" field is free text
// (e.g. "auf Anfrage") and can't be turned into a valid structured price
// without risking incorrect data.
return result;
}
export function eventJsonLd(args: {
event: Event;
description: string;
imageUrl?: string;
joinUrl?: string;
siteUrl: string;
providerName: string;
booking: BookingSetting | null | undefined;
}): JsonLdValue | null {
const { event } = args;
// Private single-session bookings must never surface as a public Event
// (see section 18) — defense in depth alongside the page-level checks
// that already keep them out of public listings entirely.
if (event.isPrivateBooking) return null;
if (!event.date) return null;
const start = new Date(event.startTime || event.date);
const isOnline = Boolean(event.isOnline);
const result: JsonLdValue = {
"@context": "https://schema.org",
"@type": "Event",
name: event.title,
description: args.description,
startDate: toBerlinOffsetISOString(start),
eventStatus: "https://schema.org/EventScheduled",
eventAttendanceMode: isOnline ? "https://schema.org/OnlineEventAttendanceMode" : "https://schema.org/OfflineEventAttendanceMode",
url: `${args.siteUrl}/termine/${event.slug}`,
organizer: { "@type": "Organization", name: args.providerName, url: args.siteUrl },
};
if (event.endTime) result.endDate = toBerlinOffsetISOString(new Date(event.endTime));
if (args.imageUrl) result.image = args.imageUrl;
if (isOnline) {
result.location = { "@type": "VirtualLocation", url: args.joinUrl ?? result.url };
} else if (hasFullAddress(args.booking)) {
result.location = {
"@type": "Place",
name: event.location || args.booking.locationName || args.providerName,
address: postalAddress(args.booking),
};
} else if (event.location) {
// No structured address on file, but the event itself names a place —
// still valid schema.org (address is optional on Place).
result.location = { "@type": "Place", name: event.location };
}
return result;
}
export function articleJsonLd(args: {
post: Post;
description: string;
imageUrl?: string;
siteUrl: string;
providerName: string;
}): JsonLdValue {
const url = `${args.siteUrl}/aktuelles/${args.post.slug}`;
return {
"@context": "https://schema.org",
"@type": "BlogPosting",
headline: args.post.title,
description: args.description,
url,
mainEntityOfPage: url,
datePublished: new Date(args.post.publishDate ?? args.post.createdAt).toISOString(),
dateModified: new Date(args.post.updatedAt).toISOString(),
author: { "@type": "Person", name: args.post.author?.trim() || args.providerName },
publisher: { "@type": "Organization", name: args.providerName, url: args.siteUrl },
...(args.imageUrl ? { image: args.imageUrl } : {}),
};
}
/** Renders one or more JSON-LD objects as server-side <script> tags. Filters out any null entries so callers can pass conditional builders directly. */
export function JsonLd({ data }: { data: JsonLdValue | JsonLdValue[] | null | (JsonLdValue | null)[] }) {
const items = (Array.isArray(data) ? data : [data]).filter((item): item is JsonLdValue => Boolean(item));
if (items.length === 0) return null;
return (
<>
{items.map((item, index) => (
<script key={index} type="application/ld+json" dangerouslySetInnerHTML={{ __html: toSafeJsonLdString(item) }} />
))}
</>
);
}
+52
View File
@@ -0,0 +1,52 @@
import type { Metadata } from "next";
import { siteConfig } from "@/lib/site";
import { getSiteUrl, isSiteIndexable } from "./config";
/**
* Single shared Metadata builder used by every public page's
* generateMetadata — guarantees every page gets its own canonical, robots,
* Open Graph and Twitter/X card data instead of copy-pasted boilerplate
* (and the accidental duplicate-description bugs that come with that).
*
* `path` is the page's path relative to the site root (e.g.
* "/angebote/doula-begleitung", or "" for the homepage).
*/
export async function buildMetadata(args: {
title: string;
description: string;
path: string;
ogImageUrl?: string;
keywords?: string;
noindex?: boolean;
type?: "website" | "article";
}): Promise<Metadata> {
const [siteUrl, sitewideIndexable] = await Promise.all([getSiteUrl(), isSiteIndexable()]);
const canonical = `${siteUrl}${args.path}`;
const indexable = !args.noindex && sitewideIndexable;
const images = args.ogImageUrl ? [{ url: args.ogImageUrl }] : undefined;
return {
title: args.title,
description: args.description,
keywords: args.keywords,
alternates: { canonical },
robots: indexable
? { index: true, follow: true }
: { index: false, follow: false },
openGraph: {
title: args.title,
description: args.description,
url: canonical,
siteName: siteConfig.name,
type: args.type ?? "website",
images,
locale: siteConfig.locale,
},
twitter: {
card: images ? "summary_large_image" : "summary",
title: args.title,
description: args.description,
images: images?.map((image) => image.url),
},
};
}
+23
View File
@@ -0,0 +1,23 @@
import { cache } from "react";
import { getCMS } from "@/lib/payload/getPayload";
/**
* Looks up a CMS-configured redirect for a changed slug (see
* collections/Redirects.ts). Only called from the three dynamic [slug]
* detail pages right before they'd otherwise 404 — not a catch-all
* middleware, so this never adds a database lookup to the other ~30 routes
* that never need it.
*/
export const resolveRedirect = cache(async (fromPath: string): Promise<{ to: string; permanent: boolean } | null> => {
const payload = await getCMS();
const { docs } = await payload.find({
collection: "redirects",
where: { and: [{ fromPath: { equals: fromPath } }, { enabled: { equals: true } }] },
limit: 1,
depth: 0,
overrideAccess: false,
});
const redirect = docs[0];
if (!redirect) return null;
return { to: redirect.toPath, permanent: redirect.type !== "temporary" };
});
+50
View File
@@ -0,0 +1,50 @@
import type { Media } from "@/payload-types";
import { mediaUrl } from "@/lib/payload/media";
type MediaRef = Media | number | null | undefined;
type SeoGroup =
| {
title?: string | null;
description?: string | null;
keywords?: string | null;
ogImage?: MediaRef;
}
| null
| undefined;
export type ResolvedSeo = {
title: string;
description: string;
keywords?: string;
ogImageUrl?: string;
};
/**
* Priority chain used everywhere on the site (see section 32 of the SEO
* brief): manual CMS field → content-derived fallback → nothing invented.
* `fallbackDescription` may be a thunk so callers only pay for building an
* excerpt (walking richText) when the manual field is actually empty.
*/
export function resolveSeo(args: {
seo?: SeoGroup;
fallbackTitle: string;
fallbackDescription: string | (() => string);
fallbackImage?: MediaRef;
defaultOgImage?: MediaRef;
}): ResolvedSeo {
const title = args.seo?.title?.trim() || args.fallbackTitle;
const description =
args.seo?.description?.trim() ||
(typeof args.fallbackDescription === "function" ? args.fallbackDescription() : args.fallbackDescription);
const ogImageUrl =
mediaUrl(args.seo?.ogImage, "hero") ?? mediaUrl(args.fallbackImage, "hero") ?? mediaUrl(args.defaultOgImage, "hero");
return {
title,
description,
keywords: args.seo?.keywords?.trim() || undefined,
ogImageUrl,
};
}
+32
View File
@@ -0,0 +1,32 @@
type LexicalNode = { text?: string; children?: LexicalNode[] };
function collectText(node: LexicalNode, out: string[]): void {
if (typeof node.text === "string" && node.text) out.push(node.text);
if (Array.isArray(node.children)) {
for (const child of node.children) collectText(child, out);
}
}
/** Walks a Lexical richText field's JSON (any node shape) and extracts plain text, regardless of formatting/links/lists used. */
export function plainTextFromRichText(data: unknown): string {
if (!data || typeof data !== "object") return "";
const root = (data as { root?: LexicalNode }).root;
if (!root) return "";
const parts: string[] = [];
collectText(root, parts);
return parts.join(" ").replace(/\s+/g, " ").trim();
}
/** Truncates at a word boundary rather than mid-word, for a natural-reading meta description fallback. */
export function excerpt(text: string, maxLength = 160): string {
const clean = text.replace(/\s+/g, " ").trim();
if (clean.length <= maxLength) return clean;
const truncated = clean.slice(0, maxLength);
const lastSpace = truncated.lastIndexOf(" ");
const safe = lastSpace > maxLength * 0.6 ? truncated.slice(0, lastSpace) : truncated;
return `${safe.trim()}`;
}
export function excerptFromRichText(data: unknown, maxLength = 160): string {
return excerpt(plainTextFromRichText(data), maxLength);
}