Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,89 +1,15 @@
// AK-P16b · booking-page editor UI (M06 Block E.2 + H). Minimal FUNCTIONAL form
// (bespoke polish follows D-P16): grunddata + providers + confirmation template +
// publish toggle, and the public-URL + iframe embed-code generator with copy buttons.
// AK-P16b · booking-page editor route component (M06 Block E.2 + H). Thin
// wrapper: injects the loader data + csrf into the interim ~/ui screen
// (AD-28); final Subframe optics follow David's D-P16 delta.
import { Form, useActionData, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { useActionData, useLoaderData } from "react-router";
import { useRootData } from "~/utils/data/useRootData";
import { BookingPageEditorPage } from "~/components/screens/booking/BookingPageEditorPage";
import type { BookingPageEditorLoaderData, BookingPageEditorActionData } from "../routes/BookingPageEditor.server";
function CopyField({ label, value }: { label: string; value: string }): JSX.Element {
return (
<div className="mt-2">
<span className="text-muted-foreground text-xs">{label}</span>
<div className="flex gap-2">
<input readOnly value={value} className="w-full rounded border px-2 py-1 text-xs" data-ui-id="ui.booking.pages.embed.value" />
<button type="button" className="rounded border px-2 py-1 text-xs" onClick={() => navigator.clipboard?.writeText(value)}>
⧉
</button>
</div>
</div>
);
}
export default function BookingPageEditorRoute(): JSX.Element {
const { t } = useTranslation();
export default function BookingPageEditorRoute(): React.JSX.Element {
const vm = useLoaderData<BookingPageEditorLoaderData>();
const actionData = useActionData<BookingPageEditorActionData>();
const rootData = useRootData();
const page = vm.page;
return (
<main className="mx-auto max-w-2xl px-4 py-10" data-ui-id="ui.booking.pages.editor">
<h1 className="text-foreground text-xl font-semibold">{t("bookings.pages.editor.title")}</h1>
{actionData && !actionData.ok ? (
<p role="alert" className="mt-4 text-red-600" data-ui-id="ui.booking.pages.editor.error">
{t(actionData.errorKey)}
</p>
) : null}
<Form method="post" className="mt-6 space-y-3">
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.slug")}</span>
<input name="slug" defaultValue={page?.slug ?? ""} required className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.pageTitle")}</span>
<input name="title" defaultValue={page?.title ?? ""} required className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.description")}</span>
<textarea name="description" defaultValue={page?.description ?? ""} className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.duration")}</span>
<input name="durationMinutes" type="number" defaultValue={page?.durationMinutes ?? 30} className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.providers")}</span>
<input name="providers" defaultValue={page?.providerUserIds.join(",") ?? ""} placeholder="userId1,userId2" className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.confirmationSubject")}</span>
<input name="confirmationEmailSubject" defaultValue={page?.confirmationEmailSubject ?? ""} className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.confirmationBody")}</span>
<textarea name="confirmationEmailBody" defaultValue={page?.confirmationEmailBody ?? ""} className="w-full rounded border px-2 py-1" />
</label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="isPublished" defaultChecked={page?.isPublished ?? false} />
{t("bookings.pages.editor.publishToggle")}
</label>
<button type="submit" className="rounded bg-primary px-4 py-2 text-primary-foreground" data-ui-id="ui.booking.pages.editor.save">
{t("bookings.pages.editor.save")}
</button>
</Form>
{vm.publicUrl && vm.embedCode ? (
<section className="mt-8" data-ui-id="ui.booking.pages.embed">
<h2 className="font-medium">{t("bookings.pages.embedCode")}</h2>
<CopyField label={t("bookings.pages.publicUrl")} value={vm.publicUrl} />
<CopyField label={t("bookings.pages.embedCode")} value={vm.embedCode} />
</section>
) : null}
</main>
);
return <BookingPageEditorPage vm={vm} actionErrorKey={actionData && !actionData.ok ? actionData.errorKey : null} csrf={rootData.csrf ?? null} />;
}
@@ -1,14 +1,102 @@
// AK-P16b · public booking page (M06 Block G) — minimal FUNCTIONAL UI (reachable +
// i18n + states), NOT the bespoke Calendly-polish screen (that waits on David D-P16).
// Single-page flow: pick a slot → fill the mini-form (GDPR required) → confirmation
// with an "add to calendar" (.ics) download. The component reads route-injected data
// only (no DB import); it is in apps/web so useLoaderData is allowed here.
// AK-P16b · public booking page (M06 Block G) — interim S04-style look (AD-28)
// matching the PublicFormRenderer target screens: centered card with accent bar,
// slot pills, themed submit and centered success state. Kept as plain `tcbook-*`
// CSS (no `~/ui`, no Tailwind) so the `/embed` iframe variant stays
// dependency-free — same documented deviation as PublicFormRenderer. The bespoke
// Calendly-polish screen still follows David D-BOOK/D-P16 (design-nachzug).
// Single-page flow: pick a slot → fill the mini-form (GDPR required) →
// confirmation with an "add to calendar" (.ics) download. The component reads
// route-injected data only (no DB import); useLoaderData is allowed here.
import { Form, useActionData, useLoaderData, useNavigation } from "react-router";
import { useTranslation } from "react-i18next";
import type { PublicBookingLoaderData, PublicBookingActionData } from "../routes/PublicBooking.server";
export default function PublicBookingRoute(): JSX.Element {
/**
* Self-contained styles mirroring TCFORM_CSS (S04 public form, V01 success,
* V03 submit error) with booking-specific slot pills. Driven by the same CSS
* variable names' booking twins so a tenant theme can restyle both surfaces.
*/
const TCBOOK_CSS = `
.tcbook-root { font-family: var(--tcbook-font, system-ui, -apple-system, "Segoe UI", sans-serif); color: var(--tcbook-text, #16232e); box-sizing: border-box; padding: 16px; }
.tcbook-root *, .tcbook-root *::before, .tcbook-root *::after { box-sizing: border-box; }
.tcbook-root--page { min-height: 100vh; background: #f2f4f7; padding: 48px 16px; }
.tcbook-shell { max-width: 576px; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }
.tcbook-brand { display: flex; justify-content: center; }
.tcbook-brand-badge { display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; border-radius: 50%; border: 1px solid #e0e5eb; background: #eef2f7; background: color-mix(in srgb, var(--tcbook-primary, #2563eb) 10%, #ffffff); color: var(--tcbook-primary, #2563eb); font-size: 1.15rem; font-weight: 700; }
.tcbook-card { background: var(--tcbook-bg, #ffffff); border: 1px solid #e0e5eb; border-top: 4px solid var(--tcbook-primary, #2563eb); border-radius: var(--tcbook-radius, 10px); box-shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 8px 24px rgba(16, 24, 40, 0.06); padding: 32px 28px; }
.tcbook-root h1 { font-size: 1.35rem; line-height: 1.3; margin: 0 0 6px; font-weight: 700; }
.tcbook-tenant { margin: 0 0 4px; font-size: 0.8rem; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; opacity: 0.6; }
.tcbook-root p.tcbook-description { margin: 0; font-size: 0.9rem; line-height: 1.5; opacity: 0.72; }
.tcbook-duration { margin: 8px 0 0; font-size: 0.85rem; opacity: 0.72; }
.tcbook-divider { border: 0; height: 1px; background: #e7ebef; margin: 20px 0; }
.tcbook-legend { display: block; font-weight: 600; font-size: 0.9rem; margin-bottom: 8px; padding: 0; }
.tcbook-slots { display: flex; flex-wrap: wrap; gap: 8px; margin: 0; padding: 0; border: 0; }
.tcbook-slot { position: relative; }
.tcbook-slot input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; margin: 0; }
.tcbook-slot span { display: inline-flex; align-items: center; justify-content: center; min-width: 72px; padding: 9px 14px; border: 1px solid #cfd6dd; border-radius: var(--tcbook-radius, 8px); font-size: 0.92rem; font-weight: 500; background: #fff; transition: border-color 120ms ease, background 120ms ease, color 120ms ease; }
.tcbook-slot input:checked + span { border-color: var(--tcbook-primary, #2563eb); background: var(--tcbook-primary, #2563eb); color: #fff; }
.tcbook-slot input:focus-visible + span { outline: 2px solid var(--tcbook-primary, #2563eb); outline-offset: 2px; }
.tcbook-slot input:hover:not(:checked) + span { border-color: var(--tcbook-primary, #2563eb); }
.tcbook-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.tcbook-row { display: block; margin-bottom: 14px; }
.tcbook-root input[type=text], .tcbook-root input[type=email], .tcbook-root input[type=tel] { width: 100%; padding: 10px 12px; border: 1px solid #cfd6dd; border-radius: var(--tcbook-radius, 8px); font: inherit; font-size: 0.95rem; color: inherit; background: #fff; transition: border-color 120ms ease, box-shadow 120ms ease; }
.tcbook-root input:focus { outline: none; border-color: var(--tcbook-primary, #2563eb); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15); box-shadow: 0 0 0 3px color-mix(in srgb, var(--tcbook-primary, #2563eb) 18%, transparent); }
.tcbook-root input::placeholder { color: inherit; opacity: 0.45; }
.tcbook-root input[type=checkbox] { width: 16px; height: 16px; margin: 2px 0 0; accent-color: var(--tcbook-primary, #2563eb); flex: none; }
.tcbook-consent { border: 1px solid #e0e5eb; border-radius: var(--tcbook-radius, 8px); background: #fbfcfd; padding: 12px 14px; margin-bottom: 14px; }
.tcbook-consent label { display: flex; align-items: flex-start; gap: 10px; font-weight: 500; font-size: 0.875rem; line-height: 1.45; margin: 0; cursor: pointer; }
.tcbook-error { display: flex; align-items: flex-start; gap: 10px; padding: 12px 14px; border: 1px solid #fecaca; border-radius: var(--tcbook-radius, 8px); background: #fef2f2; color: #991b1b; font-size: 0.9rem; line-height: 1.45; margin: 16px 0 0; }
.tcbook-error svg { flex: none; margin-top: 2px; }
.tcbook-empty { padding: 12px 14px; border: 1px dashed #cfd6dd; border-radius: var(--tcbook-radius, 8px); background: #fbfcfd; font-size: 0.9rem; line-height: 1.45; margin-top: 16px; opacity: 0.85; }
.tcbook-root button.tcbook-submit { display: block; width: 100%; background: var(--tcbook-primary, #2563eb); color: #fff; border: 0; padding: 12px 18px; border-radius: var(--tcbook-radius, 8px); cursor: pointer; font: inherit; font-size: 0.95rem; font-weight: 600; transition: filter 120ms ease; }
.tcbook-root button.tcbook-submit:hover:not([disabled]) { filter: brightness(0.92); }
.tcbook-root button.tcbook-submit:focus-visible { outline: 2px solid var(--tcbook-primary, #2563eb); outline-offset: 2px; }
.tcbook-root button.tcbook-submit[disabled] { opacity: 0.6; cursor: progress; }
.tcbook-success { display: flex; flex-direction: column; align-items: center; gap: 16px; text-align: center; padding: 16px 0; }
.tcbook-success-icon { display: inline-flex; align-items: center; justify-content: center; width: 56px; height: 56px; border-radius: 50%; background: #ecfdf5; color: #059669; }
.tcbook-success-message { margin: 0; font-size: 1.1rem; font-weight: 600; line-height: 1.4; }
.tcbook-success-body { margin: 0; font-size: 0.92rem; line-height: 1.5; opacity: 0.78; }
.tcbook-ics { display: inline-flex; align-items: center; justify-content: center; gap: 8px; background: var(--tcbook-primary, #2563eb); color: #fff; text-decoration: none; padding: 11px 18px; border-radius: var(--tcbook-radius, 8px); font-size: 0.92rem; font-weight: 600; transition: filter 120ms ease; }
.tcbook-ics:hover { filter: brightness(0.92); }
@media (max-width: 520px) { .tcbook-card { padding: 24px 16px; } .tcbook-root--page { padding: 24px 12px; } .tcbook-grid-2 { grid-template-columns: 1fr; } }
`;
function IconCheck(): React.JSX.Element {
return (
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M20 6 9 17l-5-5" />
</svg>
);
}
function IconAlert(): React.JSX.Element {
return (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
);
}
function BookingShell({ isEmbed, tenantName, children }: { isEmbed: boolean; tenantName: string; children: React.ReactNode }): React.JSX.Element {
return (
<main data-ui-id="ui.booking.public" className={isEmbed ? "tcbook-root" : "tcbook-root tcbook-root--page"}>
<style dangerouslySetInnerHTML={{ __html: TCBOOK_CSS }} />
<div className="tcbook-shell">
{!isEmbed ? (
<div className="tcbook-brand" aria-hidden="true">
<span className="tcbook-brand-badge">{(tenantName.trim()[0] ?? "•").toUpperCase()}</span>
</div>
) : null}
<div className="tcbook-card">{children}</div>
</div>
</main>
);
}
export default function PublicBookingRoute(): React.JSX.Element {
const vm = useLoaderData<PublicBookingLoaderData>();
const actionData = useActionData<PublicBookingActionData>();
const navigation = useNavigation();
@@ -18,73 +106,86 @@ export default function PublicBookingRoute(): JSX.Element {
if (actionData?.ok) {
const icsHref = `data:text/calendar;base64,${actionData.icsBase64}`;
return (
<main data-ui-id="ui.booking.public" className={vm.isEmbed ? "p-4" : "mx-auto max-w-xl p-6"}>
<h1 className="text-xl font-semibold">{t("bookings.public.confirmedHeadline")}</h1>
<p className="mt-2">
{t("bookings.public.confirmedBody", { title: actionData.titleLabel, date: actionData.dateLabel, time: actionData.timeLabel })}
</p>
<a data-ui-id="ui.booking.public.ics" href={icsHref} download="termin.ics" className="mt-4 inline-block underline">
{t("bookings.public.addToCalendar")}
</a>
</main>
<BookingShell isEmbed={vm.isEmbed} tenantName={vm.tenantName}>
<div className="tcbook-success">
<span className="tcbook-success-icon">
<IconCheck />
</span>
<p className="tcbook-success-message">{t("bookings.public.confirmedHeadline")}</p>
<p className="tcbook-success-body">
{t("bookings.public.confirmedBody", { title: actionData.titleLabel, date: actionData.dateLabel, time: actionData.timeLabel })}
</p>
<a data-ui-id="ui.booking.public.ics" href={icsHref} download="termin.ics" className="tcbook-ics">
{t("bookings.public.addToCalendar")}
</a>
</div>
</BookingShell>
);
}
return (
<main data-ui-id="ui.booking.public" className={vm.isEmbed ? "p-4" : "mx-auto max-w-xl p-6"}>
<BookingShell isEmbed={vm.isEmbed} tenantName={vm.tenantName}>
<header>
<p className="text-sm text-muted-foreground">{vm.tenantName}</p>
<h1 className="text-xl font-semibold">{vm.title}</h1>
{vm.description ? <p className="mt-1 text-muted-foreground">{vm.description}</p> : null}
<p className="mt-1 text-sm">{t("bookings.public.duration", { minutes: vm.durationMinutes })}</p>
<p className="tcbook-tenant">{vm.tenantName}</p>
<h1>{vm.title}</h1>
{vm.description ? <p className="tcbook-description">{vm.description}</p> : null}
<p className="tcbook-duration">{t("bookings.public.duration", { minutes: vm.durationMinutes })}</p>
</header>
{actionData && !actionData.ok ? (
<p data-ui-id="ui.booking.public.error" role="alert" className="mt-4 text-red-600">
{t(actionData.errorKey)}
<p data-ui-id="ui.booking.public.error" role="alert" className="tcbook-error">
<IconAlert />
<span>{t(actionData.errorKey)}</span>
</p>
) : null}
{vm.slots.length === 0 ? (
<p data-ui-id="ui.booking.public.empty" className="mt-6">
<p data-ui-id="ui.booking.public.empty" className="tcbook-empty">
{t("bookings.public.noSlots")}
</p>
) : (
<Form method="post" className="mt-6 space-y-4" data-ui-id="ui.booking.public.form">
<Form method="post" data-ui-id="ui.booking.public.form">
<input type="hidden" name="date" value={vm.date} />
<input type="hidden" name="tz" value={vm.timezone} />
{/* Honeypot — hidden from real users (M06 abuse guard). */}
<input type="text" name="company" tabIndex={-1} autoComplete="off" className="hidden" aria-hidden="true" />
<input type="text" name="company" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
<fieldset>
<legend className="text-sm font-medium">{t("bookings.public.chooseSlot", { date: vm.date })}</legend>
<div className="mt-2 flex flex-wrap gap-2">
<hr className="tcbook-divider" />
<fieldset className="tcbook-slots-fieldset" style={{ border: 0, margin: 0, padding: 0, marginBottom: 18 }}>
<legend className="tcbook-legend">{t("bookings.public.chooseSlot", { date: vm.date })}</legend>
<div className="tcbook-slots">
{vm.slots.map((slot, index) => (
<label key={slot.startAtIso} className="cursor-pointer rounded border px-3 py-1">
<input type="radio" name="startAt" value={slot.startAtIso} defaultChecked={index === 0} className="mr-1" />
{slot.label}
<label key={slot.startAtIso} className="tcbook-slot">
<input type="radio" name="startAt" value={slot.startAtIso} defaultChecked={index === 0} />
<span>{slot.label}</span>
</label>
))}
</div>
</fieldset>
<div className="grid grid-cols-2 gap-3">
<input name="vorname" placeholder={t("bookings.public.firstName")} className="rounded border px-3 py-2" required />
<input name="nachname" placeholder={t("bookings.public.lastName")} className="rounded border px-3 py-2" required />
<div className="tcbook-grid-2 tcbook-row">
<input name="vorname" type="text" placeholder={t("bookings.public.firstName")} required />
<input name="nachname" type="text" placeholder={t("bookings.public.lastName")} required />
</div>
<div className="tcbook-row">
<input name="email" type="email" placeholder={t("bookings.public.email")} required />
</div>
<div className="tcbook-row">
<input name="telefon" type="tel" placeholder={t("bookings.public.phone")} />
</div>
<input name="email" type="email" placeholder={t("bookings.public.email")} className="w-full rounded border px-3 py-2" required />
<input name="telefon" placeholder={t("bookings.public.phone")} className="w-full rounded border px-3 py-2" />
<label className="flex items-start gap-2 text-sm">
<input type="checkbox" name="gdpr" required className="mt-1" />
<span>{t("bookings.public.gdpr")}</span>
</label>
<div className="tcbook-consent">
<label>
<input type="checkbox" name="gdpr" required />
<span>{t("bookings.public.gdpr")}</span>
</label>
</div>
<button type="submit" disabled={submitting} data-ui-id="ui.booking.public.submit" className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50">
<button type="submit" disabled={submitting} data-ui-id="ui.booking.public.submit" className="tcbook-submit">
{submitting ? t("bookings.public.submitting") : t("bookings.public.submit")}
</button>
</Form>
)}
</main>
</BookingShell>
);
}
@@ -0,0 +1,111 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
const mocks = vi.hoisted(() => {
const tx = {
bookingPage: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn() },
bookingPageProvider: { deleteMany: vi.fn(), createMany: vi.fn() },
tenantUser: { findMany: vi.fn() },
form: { findFirst: vi.fn() },
};
return {
tx,
withTenantRLS: vi.fn(async (_tenantId: string, callback: (client: typeof tx) => Promise<unknown>) => callback(tx)),
};
});
vi.mock("~/utils/db.server", () => ({ db: {} }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
import { createBookingPage, updateBookingPage, type BookingPageInput } from "./booking.db.server";
const input: BookingPageInput = {
tenantId: "tenant-a",
createdByUserId: "admin-a",
slug: "beratung",
title: "Beratung",
description: null,
durationMinutes: 30,
confirmationEmailSubject: "Bestätigt",
confirmationEmailBody: "Dein Termin ist bestätigt.",
isPublished: true,
providerUserIds: ["provider-a"],
intakeFormId: "form-a",
};
describe("booking page tenant boundaries", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tx.bookingPage.findFirst.mockResolvedValue({ id: "page-a" });
mocks.tx.bookingPage.create.mockResolvedValue({ id: "page-a" });
mocks.tx.tenantUser.findMany.mockResolvedValue([{ userId: "provider-a" }]);
mocks.tx.form.findFirst.mockResolvedValue({ id: "form-a" });
});
it("rejects a booking page owned by another tenant before any write", async () => {
mocks.tx.bookingPage.findFirst.mockResolvedValueOnce(null);
await expect(updateBookingPage("page-from-tenant-b", input)).resolves.toBe(false);
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant-a", expect.any(Function));
expect(mocks.tx.bookingPage.findFirst).toHaveBeenCalledWith({
where: { id: "page-from-tenant-b", tenantId: "tenant-a", archivedAt: null },
select: { id: true },
});
expect(mocks.tx.tenantUser.findMany).not.toHaveBeenCalled();
expect(mocks.tx.bookingPage.update).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.deleteMany).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.createMany).not.toHaveBeenCalled();
});
it("rejects a provider who is not an active member of the tenant", async () => {
mocks.tx.tenantUser.findMany.mockResolvedValueOnce([]);
await expect(updateBookingPage("page-a", { ...input, providerUserIds: ["provider-from-tenant-b"] })).resolves.toBe(false);
expect(mocks.tx.tenantUser.findMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant-a",
userId: { in: ["provider-from-tenant-b"] },
status: TenantUserStatus.ACTIVE,
},
select: { userId: true },
});
expect(mocks.tx.bookingPage.update).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.deleteMany).not.toHaveBeenCalled();
});
it("rejects an intake form that is not visible in the tenant", async () => {
mocks.tx.form.findFirst.mockResolvedValueOnce(null);
await expect(updateBookingPage("page-a", { ...input, intakeFormId: "form-from-tenant-b" })).resolves.toBe(false);
expect(mocks.tx.form.findFirst).toHaveBeenCalledWith({
where: { id: "form-from-tenant-b", tenantId: "tenant-a", status: { not: "archived" } },
select: { id: true },
});
expect(mocks.tx.bookingPage.update).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.deleteMany).not.toHaveBeenCalled();
});
it("tenant-scopes the page update and provider replacement", async () => {
await expect(updateBookingPage("page-a", { ...input, providerUserIds: ["provider-a", "provider-a"] })).resolves.toBe(true);
expect(mocks.tx.bookingPage.update).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "page-a", tenantId: "tenant-a" } }));
expect(mocks.tx.bookingPageProvider.deleteMany).toHaveBeenCalledWith({
where: { bookingPageId: "page-a", tenantId: "tenant-a" },
});
expect(mocks.tx.bookingPageProvider.createMany).toHaveBeenCalledWith({
data: [{ tenantId: "tenant-a", bookingPageId: "page-a", providerUserId: "provider-a", displayOrder: 0 }],
});
});
it("validates references before creating a booking page", async () => {
mocks.tx.form.findFirst.mockResolvedValueOnce(null);
await expect(createBookingPage({ ...input, intakeFormId: "form-from-tenant-b" })).resolves.toBeNull();
expect(mocks.tx.bookingPage.create).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.createMany).not.toHaveBeenCalled();
});
});
@@ -3,6 +3,8 @@
// guard. Slot config + provider list feed the pure slot engine.
import { db } from "~/utils/db.server";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import type { SlotEngineConfig } from "../services/slotEngine";
export interface PublicBookingPage {
@@ -147,6 +149,8 @@ export interface AppointmentDetail {
intakeAnswers: Record<string, unknown>;
cancellationReason: string | null;
notesInternal: string | null;
/** The booking page's slot config, so the reschedule picker reuses the engine. */
pageConfig: SlotEngineConfig;
}
/** One appointment's detail (M06 Block D). Returns providerUserId so the route owner-checks. */
@@ -163,7 +167,17 @@ export async function getAppointmentDetail(tenantId: string, appointmentId: stri
intakeAnswers: true,
cancellationReason: true,
notesInternal: true,
bookingPage: { select: { title: true } },
bookingPage: {
select: {
title: true,
durationMinutes: true,
bufferBeforeMinutes: true,
bufferAfterMinutes: true,
slotIncrementMinutes: true,
minNoticeHours: true,
maxAdvanceDays: true,
},
},
},
});
if (!row) {
@@ -183,6 +197,7 @@ export async function getAppointmentDetail(tenantId: string, appointmentId: stri
intakeAnswers: (row.intakeAnswers as Record<string, unknown>) ?? {},
cancellationReason: row.cancellationReason,
notesInternal: row.notesInternal,
pageConfig: toConfig(row.bookingPage),
};
}
@@ -215,13 +230,14 @@ export interface BookingPageEdit {
confirmationEmailBody: string;
isPublished: boolean;
providerUserIds: string[];
intakeFormId: string | null;
}
/** Load a booking page for the editor (M06 Block E.2). */
export async function getBookingPageForEdit(tenantId: string, pageId: string): Promise<BookingPageEdit | null> {
const row = await db.bookingPage.findFirst({
where: { id: pageId, tenantId, archivedAt: null },
select: { id: true, slug: true, title: true, description: true, durationMinutes: true, confirmationEmailSubject: true, confirmationEmailBody: true, isPublished: true, providers: { select: { providerUserId: true } } },
select: { id: true, slug: true, title: true, description: true, durationMinutes: true, confirmationEmailSubject: true, confirmationEmailBody: true, isPublished: true, intakeFormId: true, providers: { select: { providerUserId: true } } },
});
if (!row) {
return null;
@@ -236,9 +252,25 @@ export async function getBookingPageForEdit(tenantId: string, pageId: string): P
confirmationEmailBody: row.confirmationEmailBody,
isPublished: row.isPublished,
providerUserIds: row.providers.map((p) => p.providerUserId),
intakeFormId: row.intakeFormId,
};
}
export interface IntakeFormOption {
id: string;
name: string;
}
/** Non-archived tenant forms selectable as a booking page's intake form (AK-P16c link). */
export async function listIntakeFormOptions(tenantId: string): Promise<IntakeFormOption[]> {
const rows = await db.form.findMany({
where: { tenantId, status: { not: "archived" } },
select: { id: true, name: true },
orderBy: { updatedAt: "desc" },
});
return rows.map((r) => ({ id: r.id, name: r.name }));
}
export interface BookingPageInput {
tenantId: string;
createdByUserId: string;
@@ -250,11 +282,51 @@ export interface BookingPageInput {
confirmationEmailBody: string;
isPublished: boolean;
providerUserIds: string[];
intakeFormId?: string | null;
}
async function validateBookingPageReferences(
tx: TenantRlsClient,
input: Pick<BookingPageInput, "tenantId" | "providerUserIds" | "intakeFormId">,
): Promise<string[] | null> {
const providerUserIds = [...new Set(input.providerUserIds)];
if (providerUserIds.length === 0) {
return null;
}
const activeProviders = await tx.tenantUser.findMany({
where: {
tenantId: input.tenantId,
userId: { in: providerUserIds },
status: TenantUserStatus.ACTIVE,
},
select: { userId: true },
});
const activeProviderIds = new Set(activeProviders.map((provider) => provider.userId));
if (providerUserIds.some((providerUserId) => !activeProviderIds.has(providerUserId))) {
return null;
}
if (input.intakeFormId) {
const intakeForm = await tx.form.findFirst({
where: { id: input.intakeFormId, tenantId: input.tenantId, status: { not: "archived" } },
select: { id: true },
});
if (!intakeForm) {
return null;
}
}
return providerUserIds;
}
/** Create a booking page + its provider links (M06 Block E.2). */
export async function createBookingPage(input: BookingPageInput): Promise<string> {
return db.$transaction(async (tx) => {
export async function createBookingPage(input: BookingPageInput): Promise<string | null> {
return withTenantRLS(input.tenantId, async (tx) => {
const providerUserIds = await validateBookingPageReferences(tx, input);
if (!providerUserIds) {
return null;
}
const page = await tx.bookingPage.create({
data: {
tenantId: input.tenantId,
@@ -266,21 +338,35 @@ export async function createBookingPage(input: BookingPageInput): Promise<string
confirmationEmailSubject: input.confirmationEmailSubject,
confirmationEmailBody: input.confirmationEmailBody,
isPublished: input.isPublished,
intakeFormId: input.intakeFormId ?? null,
},
select: { id: true },
});
await tx.bookingPageProvider.createMany({
data: input.providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: page.id, providerUserId, displayOrder: index })),
data: providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: page.id, providerUserId, displayOrder: index })),
});
return page.id;
});
}
/** Update a booking page + replace its provider links (M06 Block E.2). */
export async function updateBookingPage(pageId: string, input: BookingPageInput): Promise<void> {
await db.$transaction(async (tx) => {
export async function updateBookingPage(pageId: string, input: BookingPageInput): Promise<boolean> {
return withTenantRLS(input.tenantId, async (tx) => {
const page = await tx.bookingPage.findFirst({
where: { id: pageId, tenantId: input.tenantId, archivedAt: null },
select: { id: true },
});
if (!page) {
return false;
}
const providerUserIds = await validateBookingPageReferences(tx, input);
if (!providerUserIds) {
return false;
}
await tx.bookingPage.update({
where: { id: pageId },
where: { id: page.id, tenantId: input.tenantId },
data: {
slug: input.slug,
title: input.title,
@@ -289,12 +375,14 @@ export async function updateBookingPage(pageId: string, input: BookingPageInput)
confirmationEmailSubject: input.confirmationEmailSubject,
confirmationEmailBody: input.confirmationEmailBody,
isPublished: input.isPublished,
intakeFormId: input.intakeFormId ?? null,
},
});
await tx.bookingPageProvider.deleteMany({ where: { bookingPageId: pageId } });
await tx.bookingPageProvider.deleteMany({ where: { bookingPageId: page.id, tenantId: input.tenantId } });
await tx.bookingPageProvider.createMany({
data: input.providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: pageId, providerUserId, displayOrder: index })),
data: providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: page.id, providerUserId, displayOrder: index })),
});
return true;
});
}
@@ -0,0 +1,101 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadBookingContext: vi.fn(),
requireBookingPermission: vi.fn(),
validateCSRFToken: vi.fn(),
getBookingPageForEdit: vi.fn(),
createBookingPage: vi.fn(),
updateBookingPage: vi.fn(),
isSlugTaken: vi.fn(),
getTenantUsers: vi.fn(),
listIntakeFormOptions: vi.fn(),
getTranslations: vi.fn(),
}));
vi.mock("./bookingAccess.server", () => ({
BOOKING_PERMISSIONS: { admin: "bookings.admin" },
loadBookingContext: mocks.loadBookingContext,
requireBookingPermission: mocks.requireBookingPermission,
}));
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: mocks.getTranslations }));
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenantUsers: mocks.getTenantUsers }));
vi.mock("../db/booking.db.server", () => ({
getBookingPageForEdit: mocks.getBookingPageForEdit,
createBookingPage: mocks.createBookingPage,
updateBookingPage: mocks.updateBookingPage,
isSlugTaken: mocks.isSlugTaken,
listIntakeFormOptions: mocks.listIntakeFormOptions,
}));
import { bookingPageEditorAction, bookingPageEditorLoader } from "./BookingPageEditor.server";
function actionRequest(): Request {
const form = new URLSearchParams();
form.set("slug", "beratung");
form.set("title", "Beratung");
form.set("providers", "provider-a");
form.set("durationMinutes", "30");
return new Request("http://app.localhost/acme/bookings/pages/page-a", { method: "POST", body: form });
}
describe("booking page editor action tenant boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadBookingContext.mockResolvedValue({
tenantId: "tenant-a",
userId: "admin-a",
permissions: ["bookings.admin"],
hasModule: true,
});
mocks.getBookingPageForEdit.mockResolvedValue({ id: "page-a" });
mocks.isSlugTaken.mockResolvedValue(false);
mocks.updateBookingPage.mockResolvedValue(true);
mocks.getTenantUsers.mockResolvedValue([]);
mocks.listIntakeFormOptions.mockResolvedValue([]);
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
});
it("returns 404 for a foreign edit target before parsing or writing", async () => {
mocks.getBookingPageForEdit.mockResolvedValueOnce(null);
await expect(bookingPageEditorAction({ request: actionRequest(), params: { tenant: "acme", id: "page-from-tenant-b" } } as never)).rejects.toMatchObject({
status: 404,
});
expect(mocks.getBookingPageForEdit).toHaveBeenCalledWith("tenant-a", "page-from-tenant-b");
expect(mocks.isSlugTaken).not.toHaveBeenCalled();
expect(mocks.updateBookingPage).not.toHaveBeenCalled();
});
it("returns 404 when the transaction loses the tenant-owned target", async () => {
mocks.updateBookingPage.mockResolvedValueOnce(false);
await expect(bookingPageEditorAction({ request: actionRequest(), params: { tenant: "acme", id: "page-a" } } as never)).rejects.toMatchObject({
status: 404,
});
expect(mocks.updateBookingPage).toHaveBeenCalledWith("page-a", expect.objectContaining({ tenantId: "tenant-a" }));
});
it("exposes a translated title for the new-page breadcrumb", async () => {
const result = await bookingPageEditorLoader({
request: new Request("http://app.localhost/acme/bookings/pages/new"),
params: { tenant: "acme" },
} as never);
expect(result).toMatchObject({ data: { title: `bookings.pages.new | ${process.env.APP_NAME}` } });
});
it("uses the booking page name for an edit breadcrumb", async () => {
mocks.getBookingPageForEdit.mockResolvedValueOnce({ id: "page-a", slug: "beratung", title: "Erstberatung" });
const result = await bookingPageEditorLoader({
request: new Request("http://app.localhost/acme/bookings/pages/page-a"),
params: { tenant: "acme", id: "page-a" },
} as never);
expect(result).toMatchObject({ data: { title: `Erstberatung | ${process.env.APP_NAME}` } });
});
});
@@ -5,16 +5,30 @@
import { type LoaderFunctionArgs, type ActionFunctionArgs, data, redirect } from "react-router";
import { validateCSRFToken } from "~/utils/session.server";
import { getTranslations } from "~/locale/i18next.server";
import { getTenantUsers } from "~/utils/db/tenants.db.server";
import { loadBookingContext, requireBookingPermission, BOOKING_PERMISSIONS } from "./bookingAccess.server";
import { RESERVED_BOOKING_SLUGS, bookingPagesListPath, publicBookingPath, publicBookingEmbedPath, notFoundResponse } from "./bookingRoutePaths";
import { getBookingPageForEdit, createBookingPage, updateBookingPage, isSlugTaken, type BookingPageEdit } from "../db/booking.db.server";
import { getBookingPageForEdit, createBookingPage, updateBookingPage, isSlugTaken, listIntakeFormOptions, type BookingPageEdit, type IntakeFormOption } from "../db/booking.db.server";
export interface BookingPageProviderOption {
readonly id: string;
readonly label: string;
}
export interface BookingPageEditorLoaderData {
readonly title: string;
readonly mode: "new" | "edit";
readonly tenantSlug: string;
readonly page: BookingPageEdit | null;
readonly publicUrl: string | null;
readonly embedCode: string | null;
readonly providerOptions: readonly BookingPageProviderOption[];
readonly intakeFormOptions: readonly IntakeFormOption[];
/** Booking-pages list this editor sits under — back link target. */
readonly listHref: string;
/** Breadcrumb ancestor for the shell: the booking-pages list this editor sits under. */
readonly breadcrumbAncestors: readonly { readonly label: string; readonly href: string }[];
}
export type BookingPageEditorActionData = { readonly ok: false; readonly errorKey: string; readonly field?: string };
@@ -24,6 +38,7 @@ function embedSnippet(url: string): string {
}
export async function bookingPageEditorLoader({ request, params }: LoaderFunctionArgs) {
const { t } = await getTranslations(request);
const ctx = await loadBookingContext({ request, params, requireModule: true });
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
const tenantSlug = params.tenant ?? "";
@@ -36,7 +51,29 @@ export async function bookingPageEditorLoader({ request, params }: LoaderFunctio
const publicUrl = page ? `${origin}${publicBookingPath(tenantSlug, page.slug)}` : null;
const embedCode = page ? embedSnippet(`${origin}${publicBookingEmbedPath(tenantSlug, page.slug)}`) : null;
return data<BookingPageEditorLoaderData>({ mode: params.id ? "edit" : "new", tenantSlug, page, publicUrl, embedCode });
const [members, intakeFormOptions] = await Promise.all([getTenantUsers(ctx.tenantId), listIntakeFormOptions(ctx.tenantId)]);
const providerOptions: BookingPageProviderOption[] = members.map((member) => ({
id: member.userId,
label: [member.user.firstName, member.user.lastName].filter(Boolean).join(" ") || member.user.email,
}));
const pageTitle = page?.title ?? t(params.id ? "bookings.pages.editor.title" : "bookings.pages.new");
return data<BookingPageEditorLoaderData>({
title: `${pageTitle} | ${process.env.APP_NAME}`,
mode: params.id ? "edit" : "new",
tenantSlug,
page,
publicUrl,
embedCode,
providerOptions,
intakeFormOptions,
listHref: bookingPagesListPath(tenantSlug),
// Names the booking-pages list this editor was reached through, so the shell
// breadcrumb reads tenant > Termine > Booking-Seiten > <page> instead of
// jumping straight from the module crumb to the page.
breadcrumbAncestors: [{ label: t("bookings.pages.title"), href: bookingPagesListPath(tenantSlug) }],
});
}
export async function bookingPageEditorAction({ request, params }: ActionFunctionArgs) {
@@ -44,6 +81,10 @@ export async function bookingPageEditorAction({ request, params }: ActionFunctio
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
await validateCSRFToken(request);
if (params.id && !(await getBookingPageForEdit(ctx.tenantId, params.id))) {
throw notFoundResponse();
}
const form = await request.formData();
const slug = ((form.get("slug") as string | null) ?? "").trim().toLowerCase();
const title = ((form.get("title") as string | null) ?? "").trim();
@@ -77,12 +118,14 @@ export async function bookingPageEditorAction({ request, params }: ActionFunctio
confirmationEmailBody: ((form.get("confirmationEmailBody") as string | null) ?? "").trim() || "Dein Termin ist bestätigt.",
isPublished: form.get("isPublished") === "on" || form.get("isPublished") === "true",
providerUserIds,
// AK-P16c link: the selected intake form drives the real FormSubmission on booking.
intakeFormId: ((form.get("intakeFormId") as string | null) ?? "").trim() || null,
};
if (params.id) {
await updateBookingPage(params.id, input);
} else {
await createBookingPage(input);
const writeResult = params.id ? await updateBookingPage(params.id, input) : await createBookingPage(input);
if (!writeResult) {
throw notFoundResponse();
}
return redirect(bookingPagesListPath(params.tenant ?? ""));
const messageKey = params.id ? "bookings.pages.toast.saved" : "bookings.pages.toast.created";
return redirect(`${bookingPagesListPath(params.tenant ?? "")}?toast=${encodeURIComponent(messageKey)}`);
}
@@ -0,0 +1,21 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { normalizePublicBookingRedirect } from "./PublicBooking.server";
describe("public booking completion redirect", () => {
test("allows HTTPS completion URLs and local HTTP development targets", () => {
expect(normalizePublicBookingRedirect("https://customer.example/thanks?booking=1")).toBe(
"https://customer.example/thanks?booking=1",
);
expect(normalizePublicBookingRedirect("http://localhost:3000/thanks")).toBe("http://localhost:3000/thanks");
});
test("rejects scriptable, relative, malformed and oversized redirect values", () => {
expect(normalizePublicBookingRedirect("javascript:alert(document.cookie)")).toBeNull();
expect(normalizePublicBookingRedirect("data:text/html,<script>alert(1)</script>")).toBeNull();
expect(normalizePublicBookingRedirect("//attacker.example/phish")).toBeNull();
expect(normalizePublicBookingRedirect("/relative-path")).toBeNull();
expect(normalizePublicBookingRedirect("http://customer.example/phish")).toBeNull();
expect(normalizePublicBookingRedirect("x".repeat(2_049))).toBeNull();
});
});
@@ -0,0 +1,77 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionFunctionArgs } from "react-router";
const mocks = vi.hoisted(() => ({
checkAuthRateLimit: vi.fn(),
resolvePublicBookingPageRlsIdentity: vi.fn(),
resolvePublicBookingPage: vi.fn(),
submitBooking: vi.fn(),
}));
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: mocks.checkAuthRateLimit }));
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({
resolvePublicBookingPageRlsIdentity: mocks.resolvePublicBookingPageRlsIdentity,
}));
vi.mock("../db/booking.db.server", () => ({ resolvePublicBookingPage: mocks.resolvePublicBookingPage }));
vi.mock("../services/SlotQueryService.server", () => ({ loadSlotsForDate: vi.fn() }));
vi.mock("../services/slotEngine", () => ({ pickFirstAvailableProvider: vi.fn() }));
vi.mock("../services/BookingSubmitService.server", () => ({
BookingSlotTakenError: class BookingSlotTakenError extends Error {},
BookingValidationError: class BookingValidationError extends Error {},
submitBooking: mocks.submitBooking,
}));
const { publicBookingAction } = await import("./PublicBooking.server");
beforeEach(() => {
vi.clearAllMocks();
mocks.checkAuthRateLimit.mockResolvedValue({ allowed: true });
mocks.resolvePublicBookingPageRlsIdentity.mockResolvedValue({ tenantId: "tenant_1", resourceId: "page_1" });
});
describe("public booking abuse protection", () => {
it("rate-limits before page lookup, form parsing, or booking writes", async () => {
mocks.checkAuthRateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 45 });
const request = new Request("https://app.example.test/b/acme/consulting", {
method: "POST",
body: "attacker-controlled-body",
});
const response = await publicBookingAction({
request,
params: { tenant: "acme", slug: "consulting" },
context: {},
unstable_pattern: "b.$tenant.$slug",
} as ActionFunctionArgs);
expect(response.status).toBe(429);
expect(response.headers.get("Retry-After")).toBe("45");
expect(response.headers.get("Cache-Control")).toBe("no-store");
expect(mocks.checkAuthRateLimit).toHaveBeenCalledWith(expect.objectContaining({ action: "booking-submit", identifier: "acme/consulting", limit: 10 }));
expect(mocks.resolvePublicBookingPage).not.toHaveBeenCalled();
expect(mocks.submitBooking).not.toHaveBeenCalled();
});
it("enters the resolved tenant context before reading the protected booking page", async () => {
const { getRlsExecutionContext } = await import("@hivegrid/db/rls-context.server");
mocks.resolvePublicBookingPage.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1" });
return null;
});
const request = new Request("https://app.example.test/b/acme/consulting", {
method: "POST",
body: new URLSearchParams(),
});
await expect(
publicBookingAction({
request,
params: { tenant: "acme", slug: "consulting" },
context: {},
unstable_pattern: "b.$tenant.$slug",
} as ActionFunctionArgs)
).rejects.toMatchObject({ status: 404 });
expect(mocks.resolvePublicBookingPageRlsIdentity).toHaveBeenCalledWith("acme", "consulting");
});
});
@@ -12,8 +12,14 @@ import { resolvePublicBookingPage } from "../db/booking.db.server";
import { loadSlotsForDate } from "../services/SlotQueryService.server";
import { pickFirstAvailableProvider } from "../services/slotEngine";
import { submitBooking, BookingValidationError, BookingSlotTakenError } from "../services/BookingSubmitService.server";
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolvePublicBookingPageRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
import { getTranslations } from "~/locale/i18next.server";
const DEFAULT_TZ = "Europe/Berlin";
const BOOKING_SUBMIT_RATE_LIMIT = 10;
const BOOKING_SUBMIT_RATE_WINDOW_MS = 60 * 1000;
export interface PublicBookingSlotVM {
readonly startAtIso: string;
@@ -49,7 +55,14 @@ function resolveDate(url: URL, timezone: string, now: Date): string {
return formatInTimeZone(now, timezone, "yyyy-MM-dd");
}
async function buildSlots(tenantId: string, providerUserIds: string[], date: string, config: Parameters<typeof loadSlotsForDate>[0]["config"], timezone: string, now: Date): Promise<PublicBookingSlotVM[]> {
async function buildSlots(
tenantId: string,
providerUserIds: string[],
date: string,
config: Parameters<typeof loadSlotsForDate>[0]["config"],
timezone: string,
now: Date
): Promise<PublicBookingSlotVM[]> {
const slots = await loadSlotsForDate({ tenantId, providerUserIds, date, config, now });
return slots
.filter((slot) => pickFirstAvailableProvider(slot) !== null)
@@ -57,80 +70,127 @@ async function buildSlots(tenantId: string, providerUserIds: string[], date: str
}
export async function publicBookingLoader({ request, params }: LoaderFunctionArgs) {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
const identity = await resolvePublicBookingPageRlsIdentity(params.tenant ?? "", params.slug ?? "");
if (!identity) {
throw notFoundResponse();
}
const url = new URL(request.url);
const now = new Date();
const timezone = resolveTimezone(url);
const date = resolveDate(url, timezone, now);
const slots = await buildSlots(page.tenantId, page.providerUserIds, date, page.config, timezone, now);
return runWithRlsContext({ tenantId: identity.tenantId }, async () => {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
throw notFoundResponse();
}
const url = new URL(request.url);
const now = new Date();
const timezone = resolveTimezone(url);
const date = resolveDate(url, timezone, now);
const slots = await buildSlots(page.tenantId, page.providerUserIds, date, page.config, timezone, now);
const payload: PublicBookingLoaderData = {
tenantSlug: page.tenantSlug,
slug: page.slug,
title: page.title,
description: page.description,
tenantName: page.tenantName,
durationMinutes: page.durationMinutes,
date,
timezone,
slots,
isEmbed: url.pathname.endsWith("/embed"),
};
return data(payload);
const payload: PublicBookingLoaderData = {
tenantSlug: page.tenantSlug,
slug: page.slug,
title: page.title,
description: page.description,
tenantName: page.tenantName,
durationMinutes: page.durationMinutes,
date,
timezone,
slots,
isEmbed: url.pathname.endsWith("/embed"),
};
return data(payload);
});
}
export async function publicBookingAction({ request, params }: ActionFunctionArgs) {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
const rateLimit = await checkAuthRateLimit({
request,
action: "booking-submit",
identifier: `${params.tenant ?? ""}/${params.slug ?? ""}`,
limit: BOOKING_SUBMIT_RATE_LIMIT,
windowMs: BOOKING_SUBMIT_RATE_WINDOW_MS,
});
if (!rateLimit.allowed) {
return Response.json(
{ ok: false, errorKey: "bookings.error.submitFailed" },
{
status: 429,
headers: {
"Cache-Control": "no-store",
"Retry-After": String(rateLimit.retryAfterSeconds),
},
}
);
}
const identity = await resolvePublicBookingPageRlsIdentity(params.tenant ?? "", params.slug ?? "");
if (!identity) {
throw notFoundResponse();
}
const form = await request.formData();
return runWithRlsContext({ tenantId: identity.tenantId }, async () => {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
throw notFoundResponse();
}
const form = await request.formData();
// Honeypot: real users never fill this hidden field (M06 abuse guard).
if ((form.get("company") as string | null)?.trim()) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 400 });
}
// Honeypot: real users never fill this hidden field (M06 abuse guard).
if ((form.get("company") as string | null)?.trim()) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 400 });
}
const url = new URL(request.url);
const timezone = (form.get("tz") as string | null) || resolveTimezone(url);
const date = (form.get("date") as string | null) ?? "";
const startAtIso = (form.get("startAt") as string | null) ?? "";
const url = new URL(request.url);
const timezone = (form.get("tz") as string | null) || resolveTimezone(url);
const date = (form.get("date") as string | null) ?? "";
const startAtIso = (form.get("startAt") as string | null) ?? "";
const translations = await getTranslations(request);
try {
const result = await submitBooking({
page,
startAtIso,
date,
viewerTimeZone: timezone,
locale: translations.locale,
intake: {
vorname: (form.get("vorname") as string | null) ?? "",
nachname: (form.get("nachname") as string | null) ?? "",
email: (form.get("email") as string | null) ?? "",
telefon: (form.get("telefon") as string | null) ?? undefined,
gdprAccepted: form.get("gdpr") === "on" || form.get("gdpr") === "true",
},
now: new Date(),
});
const redirectUrl = normalizePublicBookingRedirect(result.redirectUrl);
if (redirectUrl) {
return redirect(redirectUrl);
}
return data<PublicBookingActionData>({
ok: true,
titleLabel: page.title,
dateLabel: formatInTimeZone(result.startAt, timezone, "dd.MM.yyyy"),
timeLabel: formatInTimeZone(result.startAt, timezone, "HH:mm"),
icsBase64: result.icsBase64,
});
} catch (error) {
if (error instanceof BookingValidationError) {
return data<PublicBookingActionData>({ ok: false, errorKey: error.code, field: error.field }, { status: 400 });
}
if (error instanceof BookingSlotTakenError) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.slotTaken" }, { status: 409 });
}
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 500 });
}
});
}
export function normalizePublicBookingRedirect(value: string | null | undefined): string | null {
if (!value || value.length > 2_048) return null;
try {
const result = await submitBooking({
page,
startAtIso,
date,
viewerTimeZone: timezone,
intake: {
vorname: (form.get("vorname") as string | null) ?? "",
nachname: (form.get("nachname") as string | null) ?? "",
email: (form.get("email") as string | null) ?? "",
telefon: (form.get("telefon") as string | null) ?? undefined,
gdprAccepted: form.get("gdpr") === "on" || form.get("gdpr") === "true",
},
now: new Date(),
});
if (result.redirectUrl) {
return redirect(result.redirectUrl);
}
return data<PublicBookingActionData>({
ok: true,
titleLabel: page.title,
dateLabel: formatInTimeZone(result.startAt, timezone, "dd.MM.yyyy"),
timeLabel: formatInTimeZone(result.startAt, timezone, "HH:mm"),
icsBase64: result.icsBase64,
});
} catch (error) {
if (error instanceof BookingValidationError) {
return data<PublicBookingActionData>({ ok: false, errorKey: error.code, field: error.field }, { status: 400 });
}
if (error instanceof BookingSlotTakenError) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.slotTaken" }, { status: 409 });
}
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 500 });
const url = new URL(value);
const localDevelopmentUrl = url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
if (url.protocol !== "https:" && !localDevelopmentUrl) return null;
return url.toString();
} catch {
return null;
}
}
@@ -39,6 +39,21 @@ describe("booking route authorization boundary", () => {
expect(source).toContain('intent === "reassign"');
});
test("availability action guards permission + CSRF before parsing the form", () => {
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/availability.tsx"), "utf8");
const formDataAt = source.indexOf("await request.formData()");
expect(formDataAt).toBeGreaterThanOrEqual(0);
const permissionAt = source.indexOf("requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn)", source.indexOf("export const action"));
const csrfAt = source.indexOf("await validateCSRFToken(request)");
expect(permissionAt).toBeGreaterThanOrEqual(0);
expect(csrfAt).toBeGreaterThanOrEqual(0);
expect(permissionAt).toBeLessThan(formDataAt);
expect(csrfAt).toBeLessThan(formDataAt);
// The action only ever writes the CALLER's availability (own scope).
expect(source).toContain("providerUserId: ctx.userId");
});
test("booking-page editor action guards admin permission + CSRF before parsing the form", () => {
const source = fs.readFileSync(path.join(appRoot, "modules/booking/routes/BookingPageEditor.server.ts"), "utf8");
const formDataAt = source.indexOf("await request.formData()");
@@ -8,10 +8,14 @@
import { formatInTimeZone } from "date-fns-tz";
import { logActivity, type ActivityType } from "@hivegrid/activity";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { notify, type NotificationClient } from "@hivegrid/foundation";
import { renderSystemMessageEmail, type SystemMessageDetail } from "@hivegrid/mail";
import { getMailTranslator, type MailTranslator } from "~/locale/mail-translator.server";
import { db } from "~/utils/db.server";
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
import { assertTransition, statusAfter, notifiesCustomer, type LifecycleAction } from "./bookingTransitions";
import { buildBookingCancelledWorkflowEvent, buildCalendarCreatedWorkflowEvent } from "./bookingAutomationEvents.server";
const MINUTE_MS = 60_000;
@@ -27,6 +31,7 @@ interface AppointmentForAction {
internalCalendarEventId: string | null;
intakeAnswers: unknown;
pageTitle: string;
bookingPageSlug: string;
durationMinutes: number;
tenantName: string;
}
@@ -45,7 +50,7 @@ async function loadAppointmentForAction(tenantId: string, appointmentId: string)
timezone: true,
internalCalendarEventId: true,
intakeAnswers: true,
bookingPage: { select: { title: true, durationMinutes: true } },
bookingPage: { select: { title: true, slug: true, durationMinutes: true } },
},
});
if (!row) {
@@ -64,6 +69,7 @@ async function loadAppointmentForAction(tenantId: string, appointmentId: string)
internalCalendarEventId: row.internalCalendarEventId,
intakeAnswers: row.intakeAnswers,
pageTitle: row.bookingPage.title,
bookingPageSlug: row.bookingPage.slug,
durationMinutes: row.bookingPage.durationMinutes,
tenantName: tenant?.name ?? "",
};
@@ -77,7 +83,21 @@ function bookerEmail(intakeAnswers: unknown): string | null {
return null;
}
async function recordActivity(tenantId: string, appt: AppointmentForAction, activityType: ActivityType, summaryText: string, actorUserId: string | null): Promise<void> {
function bookerLocale(intakeAnswers: unknown): string | null {
if (intakeAnswers && typeof intakeAnswers === "object" && "locale" in intakeAnswers) {
const locale = (intakeAnswers as { locale?: unknown }).locale;
return typeof locale === "string" && locale.trim() ? locale.trim() : null;
}
return null;
}
async function recordActivity(
tenantId: string,
appt: AppointmentForAction,
activityType: ActivityType,
summaryText: string,
actorUserId: string | null
): Promise<void> {
if (!appt.kontaktId) {
return;
}
@@ -95,39 +115,114 @@ async function recordActivity(tenantId: string, appt: AppointmentForAction, acti
async function notifyProvider(tenantId: string, providerUserId: string, messageKey: string, appointmentId: string): Promise<void> {
await notify(
{ tenantId, userId: providerUserId, channel: "IN_APP", category: "bookings", messageKey, sourceKey: `${messageKey}:${appointmentId}`, payloadMetadata: { appointmentId } },
{
tenantId,
userId: providerUserId,
channel: "IN_APP",
category: "bookings",
messageKey,
sourceKey: `${messageKey}:${appointmentId}`,
payloadMetadata: { appointmentId },
},
db as unknown as NotificationClient
).catch(() => undefined);
}
async function sendLifecycleMail(appt: AppointmentForAction, subject: string, body: string): Promise<boolean> {
async function sendLifecycleMail(
appt: AppointmentForAction,
input: {
readonly kind: "cancelled" | "reassigned" | "rescheduled";
readonly newWhen?: string;
readonly reason?: string;
}
): Promise<boolean> {
const to = bookerEmail(appt.intakeAnswers);
if (!to) {
return false;
}
try {
await sendEmailMailjet({ data: { to, subject, body: body.replace(/\r?\n/gu, "<br/>") } });
const { t, locale } = await getMailTranslator(bookerLocale(appt.intakeAnswers));
const content = lifecycleMailContent(t, appt, input);
const rendered = renderSystemMessageEmail({
locale,
subject: content.subject,
previewText: content.intro,
eyebrow: content.eyebrow,
title: content.title,
intro: content.intro,
details: content.details,
notice: content.notice,
noticeTone: content.notice ? "info" : undefined,
});
await sendEmailMailjet({
data: {
to,
subject: content.subject,
body: rendered.html,
text: rendered.text,
},
});
return true;
} catch {
return false;
}
}
function lifecycleMailContent(
t: MailTranslator,
appt: AppointmentForAction,
input: {
readonly kind: "cancelled" | "reassigned" | "rescheduled";
readonly newWhen?: string;
readonly reason?: string;
}
): {
readonly subject: string;
readonly eyebrow: string;
readonly title: string;
readonly intro: string;
readonly details: readonly SystemMessageDetail[];
readonly notice?: string;
} {
const prefix = `booking.${input.kind}`;
const details: SystemMessageDetail[] = [{ label: t(`${prefix}.fields.appointment`), value: appt.pageTitle }];
if (input.kind === "rescheduled") {
details.push({ label: t(`${prefix}.fields.previous`), value: whenLabel(appt) }, { label: t(`${prefix}.fields.new`), value: input.newWhen ?? "" });
} else {
details.push({ label: t(`${prefix}.fields.when`), value: whenLabel(appt) });
}
return {
subject: t(`${prefix}.subject`, { title: appt.pageTitle }),
eyebrow: t(`${prefix}.eyebrow`),
title: t(`${prefix}.title`),
intro: t(`${prefix}.intro`),
details,
notice: input.reason ? t(`${prefix}.reason`, { reason: input.reason }) : undefined,
};
}
function whenLabel(appt: AppointmentForAction): string {
return formatInTimeZone(appt.startAt, appt.timezone, "dd.MM.yyyy HH:mm");
}
/** Mark a past appointment as held (M06 D). */
export async function markAppointmentHeld(tenantId: string, appointmentId: string, actorUserId: string): Promise<void> {
await applyStatusOnly(tenantId, appointmentId, "mark_held", actorUserId, "appointment_held", "als stattgefunden markiert");
await applyStatusOnly(tenantId, appointmentId, "mark_held", actorUserId, "appointment_held", "activity.runtime.booking.held");
}
/** Mark an appointment as no-show (M06 D). */
export async function markAppointmentNoShow(tenantId: string, appointmentId: string, actorUserId: string): Promise<void> {
await applyStatusOnly(tenantId, appointmentId, "mark_no_show", actorUserId, "appointment_no_show", "als nicht erschienen markiert");
await applyStatusOnly(tenantId, appointmentId, "mark_no_show", actorUserId, "appointment_no_show", "activity.runtime.booking.noShow");
}
async function applyStatusOnly(tenantId: string, appointmentId: string, action: LifecycleAction, actorUserId: string, activityType: ActivityType, summaryVerb: string): Promise<void> {
async function applyStatusOnly(
tenantId: string,
appointmentId: string,
action: LifecycleAction,
actorUserId: string,
activityType: ActivityType,
summaryKey: string
): Promise<void> {
const appt = await loadAppointmentForAction(tenantId, appointmentId);
if (!appt) {
return;
@@ -137,35 +232,64 @@ async function applyStatusOnly(tenantId: string, appointmentId: string, action:
if (next) {
await db.appointment.update({ where: { id: appt.id }, data: { status: next } });
}
await recordActivity(tenantId, appt, activityType, `Termin ${appt.pageTitle} (${whenLabel(appt)}) ${summaryVerb}`, actorUserId);
await recordActivity(tenantId, appt, activityType, summaryKey, actorUserId);
}
/** Cancel an appointment with a reason + auto-mail (M06 D / I). */
export async function cancelAppointment(input: { tenantId: string; appointmentId: string; reason: string; byKind: "customer" | "provider" | "system"; actorUserId: string | null }): Promise<void> {
export async function cancelAppointment(input: {
tenantId: string;
appointmentId: string;
reason: string;
byKind: "customer" | "provider" | "system";
actorUserId: string | null;
}): Promise<void> {
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
if (!appt) {
return;
}
assertTransition(appt.status, "cancel");
const cancelledAt = new Date();
await db.$transaction(async (tx) => {
await tx.appointment.update({
where: { id: appt.id },
data: { status: "cancelled", cancelledAt: new Date(), cancelledByKind: input.byKind, cancellationReason: input.reason },
data: { status: "cancelled", cancelledAt, cancelledByKind: input.byKind, cancellationReason: input.reason },
});
if (appt.internalCalendarEventId) {
// Free the slot: archive the local mirror so it stops blocking availability.
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { archivedAt: new Date(), isBusyForAvailability: false } });
}
await publishOutboxEvent(
tx as unknown as OutboxPublisherTransaction,
buildBookingCancelledWorkflowEvent({
tenantId: input.tenantId,
appointmentId: appt.id,
bookingPageId: appt.bookingPageId,
bookingPageSlug: appt.bookingPageSlug,
providerUserId: appt.providerUserId,
cancelledByKind: input.byKind,
cancellationReason: input.reason,
cancelledAt,
actorUserId: input.actorUserId,
})
);
});
await sendLifecycleMail(appt, `Termin storniert: ${appt.pageTitle}`, `Dein Termin am ${whenLabel(appt)} wurde storniert.\nGrund: ${input.reason}`);
await recordActivity(input.tenantId, appt, "appointment_cancelled", `Termin ${appt.pageTitle} (${whenLabel(appt)}) storniert: ${input.reason}`, input.actorUserId);
await sendLifecycleMail(appt, {
kind: "cancelled",
reason: input.reason,
});
await recordActivity(input.tenantId, appt, "appointment_cancelled", "activity.runtime.booking.cancelled", input.actorUserId);
if (notifiesCustomer("cancel")) {
await notifyProvider(input.tenantId, appt.providerUserId, "bookings.status.cancelled", appt.id);
}
}
/** Reschedule to a new start time: supersede the old appointment with a successor (M06 D). */
export async function rescheduleAppointment(input: { tenantId: string; appointmentId: string; newStartAt: Date; actorUserId: string }): Promise<{ newAppointmentId: string }> {
export async function rescheduleAppointment(input: {
tenantId: string;
appointmentId: string;
newStartAt: Date;
actorUserId: string;
}): Promise<{ newAppointmentId: string }> {
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
if (!appt) {
throw new Error("appointment_not_found");
@@ -194,16 +318,42 @@ export async function rescheduleAppointment(input: { tenantId: string; appointme
select: { id: true },
});
const calendarEvent = await tx.calendarEvent.create({
data: { tenantId: input.tenantId, userId: appt.providerUserId, source: "hivegrid_internal", title: appt.pageTitle, startsAt: input.newStartAt, endsAt: newEndAt, isBusyForAvailability: true, internalEntityLink: { type: "booking_appointment", id: successor.id } },
data: {
tenantId: input.tenantId,
userId: appt.providerUserId,
source: "hivegrid_internal",
title: appt.pageTitle,
startsAt: input.newStartAt,
endsAt: newEndAt,
isBusyForAvailability: true,
internalEntityLink: { type: "booking_appointment", id: successor.id },
},
select: { id: true },
});
await tx.appointment.update({ where: { id: successor.id }, data: { internalCalendarEventId: calendarEvent.id } });
await publishOutboxEvent(
tx as unknown as OutboxPublisherTransaction,
buildCalendarCreatedWorkflowEvent({
tenantId: input.tenantId,
calendarEventId: calendarEvent.id,
userId: input.actorUserId,
calendarKey: "hauptkalender",
eventKind: "termin",
source: "booking_reschedule",
sourceEntityId: successor.id,
startsAt: input.newStartAt,
endsAt: newEndAt,
})
);
return successor.id;
});
const newWhen = formatInTimeZone(input.newStartAt, appt.timezone, "dd.MM.yyyy HH:mm");
await sendLifecycleMail(appt, `Termin verschoben: ${appt.pageTitle}`, `Dein Termin wurde von ${whenLabel(appt)} auf ${newWhen} verschoben.`);
await recordActivity(input.tenantId, appt, "appointment_rescheduled", `Termin ${appt.pageTitle} verschoben von ${whenLabel(appt)} auf ${newWhen}`, input.actorUserId);
await sendLifecycleMail(appt, {
kind: "rescheduled",
newWhen,
});
await recordActivity(input.tenantId, appt, "appointment_rescheduled", "activity.runtime.booking.rescheduled", input.actorUserId);
await notifyProvider(input.tenantId, appt.providerUserId, "bookings.status.rescheduled", newAppointmentId);
return { newAppointmentId };
}
@@ -222,7 +372,9 @@ export async function reassignAppointment(input: { tenantId: string; appointment
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { userId: input.newProviderUserId } });
}
});
await sendLifecycleMail(appt, `Termin: neuer Ansprechpartner — ${appt.pageTitle}`, `Dein Termin am ${whenLabel(appt)} wird von einem anderen Mitarbeiter betreut.`);
await recordActivity(input.tenantId, appt, "appointment_rescheduled", `Termin ${appt.pageTitle} (${whenLabel(appt)}) neu zugewiesen`, input.actorUserId);
await sendLifecycleMail(appt, {
kind: "reassigned",
});
await recordActivity(input.tenantId, appt, "appointment_rescheduled", "activity.runtime.booking.reassigned", input.actorUserId);
await notifyProvider(input.tenantId, input.newProviderUserId, "bookings.status.scheduled", appt.id);
}
@@ -13,14 +13,18 @@
import { formatInTimeZone } from "date-fns-tz";
import { logActivity } from "@hivegrid/activity";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { db } from "~/utils/db.server";
import { createLead } from "~/utils/integrations/leads/leadService.server";
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
import { renderSystemMessageEmail } from "@hivegrid/mail";
import { getMailTranslator } from "~/locale/mail-translator.server";
import type { PublicBookingPage } from "../db/booking.db.server";
import { findKontaktIdByEmail } from "../db/booking.db.server";
import { loadSlotsForDate } from "./SlotQueryService.server";
import { pickFirstAvailableProvider } from "./slotEngine";
import { buildIcs, icsToBase64 } from "./ics";
import { buildBookingBookedWorkflowEvents } from "./bookingAutomationEvents.server";
const MINUTE_MS = 60_000;
@@ -59,6 +63,7 @@ export interface BookingSubmitInput {
readonly date: string;
/** Booker's IANA timezone (for display + the appointment record). */
readonly viewerTimeZone: string;
readonly locale?: string;
readonly intake: BookingIntake;
readonly now: Date;
}
@@ -129,6 +134,7 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
email: input.intake.email.trim(),
telefon: input.intake.telefon?.trim() ?? null,
gdprAccepted: true,
locale: input.locale ?? "de",
};
const eventTitle = renderTemplate(page.internalEventTitleTemplate ?? "{{booking_page.title}}", {
"booking_page.title": page.title,
@@ -206,6 +212,19 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
where: { id: appointment.id },
data: { internalCalendarEventId: calendarEvent.id, formSubmissionId: formSubmission?.id ?? null },
});
for (const event of buildBookingBookedWorkflowEvents({
tenantId: page.tenantId,
appointmentId: appointment.id,
bookingPageId: page.pageId,
bookingPageSlug: page.slug,
providerUserId,
calendarEventId: calendarEvent.id,
startAt,
endAt,
kontaktId,
})) {
await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, event);
}
return appointment.id;
},
{ isolationLevel: "Serializable" }
@@ -238,7 +257,7 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
}
// 4) Activity on the contact/lead (M06 J.4). Best-effort — never break the booking.
const activitySubject = kontaktId ? ({ type: "contact" as const, id: kontaktId }) : leadId ? ({ type: "lead" as const, id: leadId }) : null;
const activitySubject = kontaktId ? { type: "contact" as const, id: kontaktId } : leadId ? { type: "lead" as const, id: leadId } : null;
if (activitySubject) {
await logActivity({
tenantId: page.tenantId,
@@ -247,15 +266,26 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
activityType: "appointment_scheduled",
subjectType: activitySubject.type,
subjectId: activitySubject.id,
summaryText: `Termin ${page.title} am ${formatInTimeZone(startAt, input.viewerTimeZone, "dd.MM.yyyy HH:mm")} gebucht`,
metadata: { appointmentId, bookingPageId: page.pageId, leadId, kontaktId },
summaryText: "activity.runtime.booking.scheduled",
metadata: {
appointmentId,
bookingPageId: page.pageId,
bookingPageTitle: page.title,
startAt: startAt.toISOString(),
timezone: input.viewerTimeZone,
leadId,
kontaktId,
},
}).catch(() => undefined);
}
// 5) Confirmation mail + .ics (best-effort, M06 I.3).
const icsBase64 = await sendConfirmation({ input, providerUserId, startAt, endAt, appointmentId }).catch(async () => {
await db.appointment
.update({ where: { id: appointmentId }, data: { notesInternal: `Bestätigungsmail an ${input.intake.email} konnte nicht versendet werden — Endkunde bitte direkt informieren.` } })
.update({
where: { id: appointmentId },
data: { notesInternal: `Bestätigungsmail an ${input.intake.email} konnte nicht versendet werden — Endkunde bitte direkt informieren.` },
})
.catch(() => undefined);
return buildBookingIcs({ input, providerUserId, startAt, endAt, appointmentId });
});
@@ -279,8 +309,14 @@ function buildBookingIcs(args: { input: BookingSubmitInput; providerUserId: stri
return icsToBase64(ics);
}
async function sendConfirmation(args: { input: BookingSubmitInput; providerUserId: string; startAt: Date; endAt: Date; appointmentId: string }): Promise<string> {
const { input, startAt, endAt } = args;
async function sendConfirmation(args: {
input: BookingSubmitInput;
providerUserId: string;
startAt: Date;
endAt: Date;
appointmentId: string;
}): Promise<string> {
const { input, startAt } = args;
const { page } = input;
const icsBase64 = buildBookingIcs(args);
@@ -298,12 +334,31 @@ async function sendConfirmation(args: { input: BookingSubmitInput; providerUserI
};
const subject = renderTemplate(page.confirmationEmailSubject, vars);
const body = renderTemplate(page.confirmationEmailBody, vars);
const { t, locale } = await getMailTranslator(input.locale);
const rendered = renderSystemMessageEmail({
locale,
brand: { tenantName: page.tenantName },
subject,
previewText: t("booking.confirmation.previewText", { company: page.tenantName }),
eyebrow: t("booking.confirmation.eyebrow"),
title: t("booking.confirmation.title"),
intro: body,
details: [
{ label: t("booking.confirmation.fields.appointment"), value: page.title },
{ label: t("booking.confirmation.fields.date"), value: vars["appointment.date"] ?? "" },
{ label: t("booking.confirmation.fields.time"), value: t("booking.confirmation.timeValue", { time: vars["appointment.time"] ?? "" }) },
{ label: t("booking.confirmation.fields.duration"), value: t("booking.confirmation.durationValue", { minutes: page.durationMinutes }) },
{ label: t("booking.confirmation.fields.company"), value: page.tenantName },
],
notice: t("booking.confirmation.notice"),
});
await sendEmailMailjet({
data: {
to: input.intake.email.trim(),
subject,
body: body.replace(/\r?\n/gu, "<br/>"),
body: rendered.html,
text: rendered.text,
tenantId: page.tenantId,
attachments: [{ filename: "termin.ics", content: icsBase64, disposition: "attachment" }],
},
@@ -0,0 +1,91 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
db: {
availabilityRule: { findMany: vi.fn() },
availabilityException: { findMany: vi.fn() },
appointment: { findMany: vi.fn() },
calendarEvent: { findMany: vi.fn() },
},
computeSlots: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({ db: mocks.db }));
vi.mock("./slotEngine", () => ({ computeSlots: mocks.computeSlots }));
import { loadSlotsForDate } from "./SlotQueryService.server";
describe("SlotQueryService.server", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.db.availabilityRule.findMany.mockResolvedValue([]);
mocks.db.availabilityException.findMany.mockResolvedValue([]);
mocks.db.appointment.findMany.mockResolvedValue([]);
mocks.db.calendarEvent.findMany.mockResolvedValue([]);
mocks.computeSlots.mockReturnValue([]);
});
it("loads any number of providers with four bulk queries", async () => {
const startAt = new Date("2026-07-20T09:00:00.000Z");
const endAt = new Date("2026-07-20T10:00:00.000Z");
mocks.db.availabilityRule.findMany.mockResolvedValue([
{ providerUserId: "provider_2", dayOfWeek: "monday", startTime: "09:00", endTime: "17:00", timezone: "Europe/Berlin" },
]);
mocks.db.appointment.findMany.mockResolvedValue([{ providerUserId: "provider_1", startAt, endAt }]);
mocks.db.calendarEvent.findMany.mockResolvedValue([
{ userId: "provider_2", startsAt: startAt, endsAt: endAt, isBusyForAvailability: true, archivedAt: null },
]);
await loadSlotsForDate({
tenantId: "tenant_1",
providerUserIds: ["provider_1", "provider_2"],
date: "2026-07-20",
now: new Date("2026-07-10T00:00:00.000Z"),
config: {
durationMinutes: 30,
bufferBeforeMinutes: 0,
bufferAfterMinutes: 0,
slotIncrementMinutes: 15,
minNoticeHours: 4,
maxAdvanceDays: 60,
},
});
expect(mocks.db.availabilityRule.findMany).toHaveBeenCalledTimes(1);
expect(mocks.db.availabilityException.findMany).toHaveBeenCalledTimes(1);
expect(mocks.db.appointment.findMany).toHaveBeenCalledTimes(1);
expect(mocks.db.calendarEvent.findMany).toHaveBeenCalledTimes(1);
expect(mocks.db.availabilityRule.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: { tenantId: "tenant_1", providerUserId: { in: ["provider_1", "provider_2"] } } }),
);
expect(mocks.computeSlots).toHaveBeenCalledWith(
expect.objectContaining({
providers: [
expect.objectContaining({ providerUserId: "provider_1", busyIntervals: [{ from: startAt, to: endAt }] }),
expect.objectContaining({ providerUserId: "provider_2", rules: [expect.objectContaining({ dayOfWeek: "monday" })], busyIntervals: [{ from: startAt, to: endAt }] }),
],
}),
);
});
it("short-circuits without querying when no provider is configured", async () => {
await expect(
loadSlotsForDate({
tenantId: "tenant_1",
providerUserIds: [],
date: "2026-07-20",
now: new Date("2026-07-10T00:00:00.000Z"),
config: {
durationMinutes: 30,
bufferBeforeMinutes: 0,
bufferAfterMinutes: 0,
slotIncrementMinutes: 15,
minNoticeHours: 4,
maxAdvanceDays: 60,
},
}),
).resolves.toEqual([]);
expect(mocks.db.availabilityRule.findMany).not.toHaveBeenCalled();
expect(mocks.computeSlots).not.toHaveBeenCalled();
});
});
@@ -37,44 +37,68 @@ function dayWindow(date: string): { from: Date; to: Date } {
return { from: new Date(midnightUtc - DAY_MS), to: new Date(midnightUtc + 2 * DAY_MS) };
}
/** Load one provider's rules, exceptions and busy intervals for the day. */
async function loadProviderInput(tenantId: string, providerUserId: string, date: string): Promise<ProviderAvailabilityInput> {
function groupByProvider<T>(rows: readonly T[], providerId: (row: T) => string): Map<string, T[]> {
const grouped = new Map<string, T[]>();
for (const row of rows) {
const id = providerId(row);
const group = grouped.get(id);
if (group) group.push(row);
else grouped.set(id, [row]);
}
return grouped;
}
/** Load all providers' rules, exceptions and busy intervals in four queries. */
async function loadProviderInputs(tenantId: string, providerUserIds: readonly string[], date: string): Promise<ProviderAvailabilityInput[]> {
const window = dayWindow(date);
const [rules, exceptions, appointments, events] = await Promise.all([
db.availabilityRule.findMany({
where: { tenantId, providerUserId },
select: { dayOfWeek: true, startTime: true, endTime: true, timezone: true },
where: { tenantId, providerUserId: { in: [...providerUserIds] } },
select: { providerUserId: true, dayOfWeek: true, startTime: true, endTime: true, timezone: true },
}),
db.availabilityException.findMany({
where: { tenantId, providerUserId, date: new Date(`${date}T00:00:00Z`) },
select: { date: true, kind: true, startTime: true, endTime: true, timezone: true },
where: { tenantId, providerUserId: { in: [...providerUserIds] }, date: new Date(`${date}T00:00:00Z`) },
select: { providerUserId: true, date: true, kind: true, startTime: true, endTime: true, timezone: true },
}),
db.appointment.findMany({
where: { tenantId, providerUserId, status: { in: [...OCCUPYING_STATUSES] }, startAt: { gte: window.from, lte: window.to } },
select: { startAt: true, endAt: true },
where: { tenantId, providerUserId: { in: [...providerUserIds] }, status: { in: [...OCCUPYING_STATUSES] }, startAt: { gte: window.from, lte: window.to } },
select: { providerUserId: true, startAt: true, endAt: true },
}),
db.calendarEvent.findMany({
where: { tenantId, userId: providerUserId, isBusyForAvailability: true, archivedAt: null, startsAt: { gte: window.from, lte: window.to } },
select: { startsAt: true, endsAt: true, isBusyForAvailability: true, archivedAt: true },
where: { tenantId, userId: { in: [...providerUserIds] }, isBusyForAvailability: true, archivedAt: null, startsAt: { gte: window.from, lte: window.to } },
select: { userId: true, startsAt: true, endsAt: true, isBusyForAvailability: true, archivedAt: true },
}),
]);
const appointmentBusy: BusyInterval[] = appointments.map((a) => ({ from: a.startAt, to: a.endAt }));
const calendarBusy = extractBusyIntervals(events);
const rulesByProvider = groupByProvider(rules, (row) => row.providerUserId);
const exceptionsByProvider = groupByProvider(exceptions, (row) => row.providerUserId);
const appointmentsByProvider = groupByProvider(appointments, (row) => row.providerUserId);
const eventsByProvider = groupByProvider(events, (row) => row.userId);
return {
providerUserId,
rules: rules.map((r) => ({ dayOfWeek: r.dayOfWeek as BookingWeekday, startTime: r.startTime, endTime: r.endTime, timezone: r.timezone })) satisfies SlotRuleInput[],
exceptions: exceptions.map((e) => ({
date,
kind: e.kind as SlotExceptionInput["kind"],
startTime: e.startTime,
endTime: e.endTime,
timezone: e.timezone,
})) satisfies SlotExceptionInput[],
busyIntervals: [...appointmentBusy, ...calendarBusy],
};
return providerUserIds.map((providerUserId) => {
const providerAppointments = appointmentsByProvider.get(providerUserId) ?? [];
const appointmentBusy: BusyInterval[] = providerAppointments.map((appointment) => ({ from: appointment.startAt, to: appointment.endAt }));
const calendarBusy = extractBusyIntervals(eventsByProvider.get(providerUserId) ?? []);
return {
providerUserId,
rules: (rulesByProvider.get(providerUserId) ?? []).map((rule) => ({
dayOfWeek: rule.dayOfWeek as BookingWeekday,
startTime: rule.startTime,
endTime: rule.endTime,
timezone: rule.timezone,
})) satisfies SlotRuleInput[],
exceptions: (exceptionsByProvider.get(providerUserId) ?? []).map((exception) => ({
date,
kind: exception.kind as SlotExceptionInput["kind"],
startTime: exception.startTime,
endTime: exception.endTime,
timezone: exception.timezone,
})) satisfies SlotExceptionInput[],
busyIntervals: [...appointmentBusy, ...calendarBusy],
};
});
}
/** Compute the bookable slots for a booking page's providers on a given local day. */
@@ -82,6 +106,6 @@ export async function loadSlotsForDate(input: SlotQueryInput): Promise<ComputedS
if (input.providerUserIds.length === 0) {
return [];
}
const providers = await Promise.all(input.providerUserIds.map((id) => loadProviderInput(input.tenantId, id, input.date)));
const providers = await loadProviderInputs(input.tenantId, input.providerUserIds, input.date);
return computeSlots({ date: input.date, now: input.now, providers, config: input.config });
}
@@ -11,15 +11,25 @@ function readArtifact(relativePath: string): string {
describe("booking DB rollout artifacts", () => {
test("hard double-booking guard uses an idempotent exclusion constraint for active appointments", () => {
const sql = readArtifact("prisma/rls/booking-constraints.sql");
// tsrange, not tstzrange: startAt/endAt are TIMESTAMP(3) (UTC by
// convention) and the timestamp->timestamptz cast is only STABLE, which
// Postgres rejects inside index expressions (42P17).
const reviewedArtifact = readArtifact("prisma/rls/booking-constraints.sql");
const baseline = readArtifact("prisma/migrations/00000000000000_hivegrid_baseline/migration.sql");
expect(sql).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
expect(sql).toContain("appointment_no_overlap");
expect(sql).toContain('EXCLUDE USING gist');
expect(sql).toContain('"providerUserId" WITH =');
expect(sql).toContain('tstzrange("startAt", "endAt", \'\'[)\'\') WITH &&');
expect(sql).toContain("WHERE (status IN (''scheduled'', ''held''))");
expect(sql).toContain("23P01");
expect(reviewedArtifact).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
expect(reviewedArtifact).toContain("23P01");
expect(baseline).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
expect(baseline).toContain("appointment_no_overlap");
expect(baseline).toContain("EXCLUDE USING gist");
// Tenant-scoped on purpose: the slot engine is tenant-scoped and demo
// tenants share provider users — a tenant-agnostic constraint leaked
// cross-tenant busy state and broke the 2026-07-17 staging rollout.
expect(baseline).toContain('"tenantId" WITH =');
expect(baseline).toContain('"providerUserId" WITH =');
expect(baseline).toContain('tsrange("startAt", "endAt", \'[)\'::text) WITH &&');
expect(baseline).not.toContain("tstzrange(");
expect(baseline).toContain("status = ANY (ARRAY['scheduled'::public.\"AppointmentStatus\", 'held'::public.\"AppointmentStatus\"])");
});
test("booking RLS artifact covers every tenant-scoped booking table and fails closed without tenant GUC", () => {
@@ -17,6 +17,7 @@ describe("booking post-booking server wiring", () => {
expect(source).toContain("appointmentId");
expect(source).toContain("data: { leadId }");
expect(source).toContain('type: "lead" as const');
expect(source).toContain('summaryText: "activity.runtime.booking.scheduled"');
});
test("public booking persists a FormSubmission when an intake form is configured", () => {
@@ -0,0 +1,78 @@
import { describe, expect, test } from "vitest";
import { buildBookingBookedWorkflowEvents, buildBookingCancelledWorkflowEvent, buildCalendarCreatedWorkflowEvent } from "./bookingAutomationEvents.server";
const START = new Date("2026-08-03T08:00:00.000Z");
const END = new Date("2026-08-03T09:00:00.000Z");
describe("booking automation workflow events", () => {
test("builds one booked and one calendar-created event from the committed booking", () => {
const events = buildBookingBookedWorkflowEvents({
tenantId: "tenant-1",
appointmentId: "appointment-1",
bookingPageId: "page-1",
bookingPageSlug: "beratung",
providerUserId: "user-1",
calendarEventId: "calendar-1",
startAt: START,
endAt: END,
kontaktId: "kontakt-1",
});
expect(events).toEqual([
expect.objectContaining({
type: "workflow.trigger.event",
dispatchKey: "workflow-trigger:booking:appointment-1:booked",
payload: expect.objectContaining({
event: "booking.appointment_booked",
data: expect.objectContaining({ appointmentId: "appointment-1", appointmentType: "beratung", providerUserId: "user-1" }),
}),
}),
expect.objectContaining({
dispatchKey: "workflow-trigger:calendar:calendar-1:created",
payload: expect.objectContaining({
event: "calendar.event_created",
data: expect.objectContaining({ calendarKey: "hauptkalender", eventKind: "termin" }),
}),
}),
]);
});
test("keeps cancellation actor and timestamp in the idempotent event", () => {
const cancelledAt = new Date("2026-08-03T07:30:00.000Z");
expect(
buildBookingCancelledWorkflowEvent({
tenantId: "tenant-1",
appointmentId: "appointment-1",
bookingPageId: "page-1",
bookingPageSlug: "wartung",
providerUserId: "user-1",
cancelledByKind: "customer",
cancellationReason: "Keine Zeit",
cancelledAt,
actorUserId: null,
})
).toMatchObject({
dispatchKey: `workflow-trigger:booking:appointment-1:cancelled:${cancelledAt.getTime()}`,
payload: { event: "booking.appointment_cancelled", data: { cancelledByKind: "customer", appointmentType: "wartung" }, userId: null },
});
});
test("builds reusable calendar-created events for non-booking sources", () => {
expect(
buildCalendarCreatedWorkflowEvent({
tenantId: "tenant-1",
calendarEventId: "calendar-2",
userId: "user-2",
calendarKey: "urlaubskalender",
eventKind: "termin",
source: "leave",
sourceEntityId: "leave-1",
startsAt: START,
endsAt: END,
})
).toMatchObject({
payload: { event: "calendar.event_created", data: { calendarKey: "urlaubskalender", source: "leave" }, userId: "user-2" },
});
});
});
@@ -0,0 +1,78 @@
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
import { buildCalendarCreatedWorkflowEvent } from "~/services/automation/automation.producer-events.server";
export { buildCalendarCreatedWorkflowEvent } from "~/services/automation/automation.producer-events.server";
export function buildBookingBookedWorkflowEvents(input: {
readonly tenantId: string;
readonly appointmentId: string;
readonly bookingPageId: string;
readonly bookingPageSlug: string;
readonly providerUserId: string;
readonly calendarEventId: string;
readonly startAt: Date;
readonly endAt: Date;
readonly kontaktId: string | null;
}) {
return [
buildWorkflowTriggerOutboxEvent({
tenantId: input.tenantId,
event: "booking.appointment_booked",
data: {
appointmentId: input.appointmentId,
bookingPageId: input.bookingPageId,
bookingPageSlug: input.bookingPageSlug,
appointmentType: input.bookingPageSlug,
terminart: input.bookingPageSlug,
providerUserId: input.providerUserId,
mitarbeiter: input.providerUserId,
startAt: input.startAt.toISOString(),
endAt: input.endAt.toISOString(),
kontaktId: input.kontaktId,
},
userId: null,
sourceId: `booking:${input.appointmentId}:booked`,
}),
buildCalendarCreatedWorkflowEvent({
tenantId: input.tenantId,
calendarEventId: input.calendarEventId,
userId: input.providerUserId,
calendarKey: "hauptkalender",
eventKind: "termin",
source: "booking",
sourceEntityId: input.appointmentId,
startsAt: input.startAt,
endsAt: input.endAt,
}),
] as const;
}
export function buildBookingCancelledWorkflowEvent(input: {
readonly tenantId: string;
readonly appointmentId: string;
readonly bookingPageId: string;
readonly bookingPageSlug: string;
readonly providerUserId: string;
readonly cancelledByKind: "customer" | "provider" | "system";
readonly cancellationReason: string;
readonly cancelledAt: Date;
readonly actorUserId: string | null;
}) {
return buildWorkflowTriggerOutboxEvent({
tenantId: input.tenantId,
event: "booking.appointment_cancelled",
data: {
appointmentId: input.appointmentId,
bookingPageId: input.bookingPageId,
bookingPageSlug: input.bookingPageSlug,
appointmentType: input.bookingPageSlug,
terminart: input.bookingPageSlug,
providerUserId: input.providerUserId,
cancelledByKind: input.cancelledByKind,
cancellationReason: input.cancellationReason,
cancelledAt: input.cancelledAt.toISOString(),
},
userId: input.actorUserId,
sourceId: `booking:${input.appointmentId}:cancelled:${input.cancelledAt.getTime()}`,
});
}