Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+89
@@ -0,0 +1,89 @@
|
||||
// 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.
|
||||
|
||||
import { Form, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
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();
|
||||
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>
|
||||
);
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
// 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.
|
||||
|
||||
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 {
|
||||
const vm = useLoaderData<PublicBookingLoaderData>();
|
||||
const actionData = useActionData<PublicBookingActionData>();
|
||||
const navigation = useNavigation();
|
||||
const { t } = useTranslation();
|
||||
const submitting = navigation.state === "submitting";
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main data-ui-id="ui.booking.public" className={vm.isEmbed ? "p-4" : "mx-auto max-w-xl p-6"}>
|
||||
<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>
|
||||
</header>
|
||||
|
||||
{actionData && !actionData.ok ? (
|
||||
<p data-ui-id="ui.booking.public.error" role="alert" className="mt-4 text-red-600">
|
||||
{t(actionData.errorKey)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{vm.slots.length === 0 ? (
|
||||
<p data-ui-id="ui.booking.public.empty" className="mt-6">
|
||||
{t("bookings.public.noSlots")}
|
||||
</p>
|
||||
) : (
|
||||
<Form method="post" className="mt-6 space-y-4" 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" />
|
||||
|
||||
<fieldset>
|
||||
<legend className="text-sm font-medium">{t("bookings.public.chooseSlot", { date: vm.date })}</legend>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{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>
|
||||
))}
|
||||
</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>
|
||||
<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>
|
||||
|
||||
<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">
|
||||
{submitting ? t("bookings.public.submitting") : t("bookings.public.submit")}
|
||||
</button>
|
||||
</Form>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
// AK-P16b · booking DB access (thin Prisma wrappers). Public reads resolve the
|
||||
// tenant from the URL slug (no logged-in user); admin reads are tenant-scoped by the
|
||||
// guard. Slot config + provider list feed the pure slot engine.
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
import type { SlotEngineConfig } from "../services/slotEngine";
|
||||
|
||||
export interface PublicBookingPage {
|
||||
tenantId: string;
|
||||
tenantName: string;
|
||||
tenantSlug: string;
|
||||
pageId: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
durationMinutes: number;
|
||||
intakeFormId: string | null;
|
||||
assignmentStrategy: string;
|
||||
confirmationEmailSubject: string;
|
||||
confirmationEmailBody: string;
|
||||
internalEventTitleTemplate: string | null;
|
||||
redirectUrlAfterBooking: string | null;
|
||||
providerUserIds: string[];
|
||||
config: SlotEngineConfig;
|
||||
}
|
||||
|
||||
const PAGE_SELECT = {
|
||||
id: true,
|
||||
slug: true,
|
||||
title: true,
|
||||
description: true,
|
||||
durationMinutes: true,
|
||||
intakeFormId: true,
|
||||
bufferBeforeMinutes: true,
|
||||
bufferAfterMinutes: true,
|
||||
slotIncrementMinutes: true,
|
||||
minNoticeHours: true,
|
||||
maxAdvanceDays: true,
|
||||
assignmentStrategy: true,
|
||||
confirmationEmailSubject: true,
|
||||
confirmationEmailBody: true,
|
||||
internalEventTitleTemplate: true,
|
||||
redirectUrlAfterBooking: true,
|
||||
} as const;
|
||||
|
||||
function toConfig(page: { durationMinutes: number; bufferBeforeMinutes: number; bufferAfterMinutes: number; slotIncrementMinutes: number; minNoticeHours: number; maxAdvanceDays: number }): SlotEngineConfig {
|
||||
return {
|
||||
durationMinutes: page.durationMinutes,
|
||||
bufferBeforeMinutes: page.bufferBeforeMinutes,
|
||||
bufferAfterMinutes: page.bufferAfterMinutes,
|
||||
slotIncrementMinutes: page.slotIncrementMinutes,
|
||||
minNoticeHours: page.minNoticeHours,
|
||||
maxAdvanceDays: page.maxAdvanceDays,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a public booking page by tenant slug + page slug. Returns null when the
|
||||
* tenant is inactive/unknown or the page is unpublished/archived (M06 G.4/K.6 — a
|
||||
* 404 with the same Klartext, never leaking tenant existence). Active providers only.
|
||||
*/
|
||||
export async function resolvePublicBookingPage(tenantSlug: string, pageSlug: string): Promise<PublicBookingPage | null> {
|
||||
const tenant = await db.tenant.findUnique({ where: { slug: tenantSlug }, select: { id: true, name: true, active: true } });
|
||||
if (!tenant || !tenant.active) {
|
||||
return null;
|
||||
}
|
||||
const page = await db.bookingPage.findFirst({
|
||||
where: { tenantId: tenant.id, slug: pageSlug, isPublished: true, archivedAt: null },
|
||||
select: PAGE_SELECT,
|
||||
});
|
||||
if (!page) {
|
||||
return null;
|
||||
}
|
||||
const providers = await db.bookingPageProvider.findMany({
|
||||
where: { bookingPageId: page.id, tenantId: tenant.id, isActive: true },
|
||||
select: { providerUserId: true },
|
||||
orderBy: { displayOrder: "asc" },
|
||||
});
|
||||
return {
|
||||
tenantId: tenant.id,
|
||||
tenantName: tenant.name,
|
||||
tenantSlug,
|
||||
pageId: page.id,
|
||||
slug: page.slug,
|
||||
title: page.title,
|
||||
description: page.description,
|
||||
durationMinutes: page.durationMinutes,
|
||||
intakeFormId: page.intakeFormId,
|
||||
assignmentStrategy: page.assignmentStrategy,
|
||||
confirmationEmailSubject: page.confirmationEmailSubject,
|
||||
confirmationEmailBody: page.confirmationEmailBody,
|
||||
internalEventTitleTemplate: page.internalEventTitleTemplate,
|
||||
redirectUrlAfterBooking: page.redirectUrlAfterBooking,
|
||||
providerUserIds: providers.map((p) => p.providerUserId),
|
||||
config: toConfig(page),
|
||||
};
|
||||
}
|
||||
|
||||
export interface AppointmentListRow {
|
||||
id: string;
|
||||
startAt: Date;
|
||||
endAt: Date;
|
||||
status: "scheduled" | "held" | "cancelled" | "no_show" | "rescheduled";
|
||||
providerUserId: string;
|
||||
pageTitle: string;
|
||||
customerName: string;
|
||||
customerEmail: string;
|
||||
}
|
||||
|
||||
function intakeName(intakeAnswers: unknown): { name: string; email: string } {
|
||||
if (intakeAnswers && typeof intakeAnswers === "object") {
|
||||
const a = intakeAnswers as { vorname?: unknown; nachname?: unknown; email?: unknown };
|
||||
const name = [a.vorname, a.nachname].filter((v) => typeof v === "string" && v).join(" ");
|
||||
return { name, email: typeof a.email === "string" ? a.email : "" };
|
||||
}
|
||||
return { name: "", email: "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* List a tenant's appointments (M06 Block C). When `ownerUserId` is set (read_own),
|
||||
* only that provider's appointments are returned — the server-side owner filter
|
||||
* (M06 K.5), never a client filter.
|
||||
*/
|
||||
export async function listAppointmentsForTenant(input: { tenantId: string; ownerUserId?: string | null }): Promise<AppointmentListRow[]> {
|
||||
const rows = await db.appointment.findMany({
|
||||
where: { tenantId: input.tenantId, ...(input.ownerUserId ? { providerUserId: input.ownerUserId } : {}) },
|
||||
select: { id: true, startAt: true, endAt: true, status: true, providerUserId: true, intakeAnswers: true, bookingPage: { select: { title: true } } },
|
||||
orderBy: { startAt: "desc" },
|
||||
take: 200,
|
||||
});
|
||||
return rows.map((r) => {
|
||||
const { name, email } = intakeName(r.intakeAnswers);
|
||||
return { id: r.id, startAt: r.startAt, endAt: r.endAt, status: r.status, providerUserId: r.providerUserId, pageTitle: r.bookingPage.title, customerName: name, customerEmail: email };
|
||||
});
|
||||
}
|
||||
|
||||
export interface AppointmentDetail {
|
||||
id: string;
|
||||
status: "scheduled" | "held" | "cancelled" | "no_show" | "rescheduled";
|
||||
providerUserId: string;
|
||||
startAt: Date;
|
||||
endAt: Date;
|
||||
timezone: string;
|
||||
pageTitle: string;
|
||||
customerName: string;
|
||||
customerEmail: string;
|
||||
intakeAnswers: Record<string, unknown>;
|
||||
cancellationReason: string | null;
|
||||
notesInternal: string | null;
|
||||
}
|
||||
|
||||
/** One appointment's detail (M06 Block D). Returns providerUserId so the route owner-checks. */
|
||||
export async function getAppointmentDetail(tenantId: string, appointmentId: string): Promise<AppointmentDetail | null> {
|
||||
const row = await db.appointment.findFirst({
|
||||
where: { id: appointmentId, tenantId },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
providerUserId: true,
|
||||
startAt: true,
|
||||
endAt: true,
|
||||
timezone: true,
|
||||
intakeAnswers: true,
|
||||
cancellationReason: true,
|
||||
notesInternal: true,
|
||||
bookingPage: { select: { title: true } },
|
||||
},
|
||||
});
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
const { name, email } = intakeName(row.intakeAnswers);
|
||||
return {
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
providerUserId: row.providerUserId,
|
||||
startAt: row.startAt,
|
||||
endAt: row.endAt,
|
||||
timezone: row.timezone,
|
||||
pageTitle: row.bookingPage.title,
|
||||
customerName: name,
|
||||
customerEmail: email,
|
||||
intakeAnswers: (row.intakeAnswers as Record<string, unknown>) ?? {},
|
||||
cancellationReason: row.cancellationReason,
|
||||
notesInternal: row.notesInternal,
|
||||
};
|
||||
}
|
||||
|
||||
export interface BookingPageListRow {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
durationMinutes: number;
|
||||
isPublished: boolean;
|
||||
providerCount: number;
|
||||
}
|
||||
|
||||
/** List a tenant's booking pages (M06 Block E.1). */
|
||||
export async function listBookingPages(tenantId: string): Promise<BookingPageListRow[]> {
|
||||
const rows = await db.bookingPage.findMany({
|
||||
where: { tenantId, archivedAt: null },
|
||||
select: { id: true, slug: true, title: true, durationMinutes: true, isPublished: true, _count: { select: { providers: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return rows.map((r) => ({ id: r.id, slug: r.slug, title: r.title, durationMinutes: r.durationMinutes, isPublished: r.isPublished, providerCount: r._count.providers }));
|
||||
}
|
||||
|
||||
export interface BookingPageEdit {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
durationMinutes: number;
|
||||
confirmationEmailSubject: string;
|
||||
confirmationEmailBody: string;
|
||||
isPublished: boolean;
|
||||
providerUserIds: string[];
|
||||
}
|
||||
|
||||
/** 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 } } },
|
||||
});
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
slug: row.slug,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
durationMinutes: row.durationMinutes,
|
||||
confirmationEmailSubject: row.confirmationEmailSubject,
|
||||
confirmationEmailBody: row.confirmationEmailBody,
|
||||
isPublished: row.isPublished,
|
||||
providerUserIds: row.providers.map((p) => p.providerUserId),
|
||||
};
|
||||
}
|
||||
|
||||
export interface BookingPageInput {
|
||||
tenantId: string;
|
||||
createdByUserId: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
durationMinutes: number;
|
||||
confirmationEmailSubject: string;
|
||||
confirmationEmailBody: string;
|
||||
isPublished: boolean;
|
||||
providerUserIds: string[];
|
||||
}
|
||||
|
||||
/** Create a booking page + its provider links (M06 Block E.2). */
|
||||
export async function createBookingPage(input: BookingPageInput): Promise<string> {
|
||||
return db.$transaction(async (tx) => {
|
||||
const page = await tx.bookingPage.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.createdByUserId,
|
||||
slug: input.slug,
|
||||
title: input.title,
|
||||
description: input.description ?? null,
|
||||
durationMinutes: input.durationMinutes,
|
||||
confirmationEmailSubject: input.confirmationEmailSubject,
|
||||
confirmationEmailBody: input.confirmationEmailBody,
|
||||
isPublished: input.isPublished,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
await tx.bookingPageProvider.createMany({
|
||||
data: input.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) => {
|
||||
await tx.bookingPage.update({
|
||||
where: { id: pageId },
|
||||
data: {
|
||||
slug: input.slug,
|
||||
title: input.title,
|
||||
description: input.description ?? null,
|
||||
durationMinutes: input.durationMinutes,
|
||||
confirmationEmailSubject: input.confirmationEmailSubject,
|
||||
confirmationEmailBody: input.confirmationEmailBody,
|
||||
isPublished: input.isPublished,
|
||||
},
|
||||
});
|
||||
await tx.bookingPageProvider.deleteMany({ where: { bookingPageId: pageId } });
|
||||
await tx.bookingPageProvider.createMany({
|
||||
data: input.providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: pageId, providerUserId, displayOrder: index })),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** True when `slug` is already used by another page in the tenant (M06 E.2 validation). */
|
||||
export async function isSlugTaken(tenantId: string, slug: string, exceptPageId?: string): Promise<boolean> {
|
||||
const row = await db.bookingPage.findFirst({ where: { tenantId, slug, ...(exceptPageId ? { NOT: { id: exceptPageId } } : {}) }, select: { id: true } });
|
||||
return row !== null;
|
||||
}
|
||||
|
||||
/** Match an incoming booker email to an existing tenant contact (M06 J.1). */
|
||||
export async function findKontaktIdByEmail(tenantId: string, email: string): Promise<string | null> {
|
||||
const normalized = email.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const row = await db.kontaktEmail.findFirst({
|
||||
where: { tenantId, email: { equals: normalized, mode: "insensitive" } },
|
||||
select: { kontaktId: true },
|
||||
});
|
||||
return row?.kontaktId ?? null;
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
// AK-P16b · booking-page editor (M06 Block E.2) — shared loader/action for the `new`
|
||||
// and `:id` routes. bookings.admin only. Validates the slug (reserved + unique) and
|
||||
// upserts the page + its provider links. The loader exposes the absolute public URL +
|
||||
// an iframe embed snippet (M06 Block H, DoD 3) for the copy-to-clipboard generator.
|
||||
|
||||
import { type LoaderFunctionArgs, type ActionFunctionArgs, data, redirect } from "react-router";
|
||||
import { validateCSRFToken } from "~/utils/session.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";
|
||||
|
||||
export interface BookingPageEditorLoaderData {
|
||||
readonly mode: "new" | "edit";
|
||||
readonly tenantSlug: string;
|
||||
readonly page: BookingPageEdit | null;
|
||||
readonly publicUrl: string | null;
|
||||
readonly embedCode: string | null;
|
||||
}
|
||||
|
||||
export type BookingPageEditorActionData = { readonly ok: false; readonly errorKey: string; readonly field?: string };
|
||||
|
||||
function embedSnippet(url: string): string {
|
||||
return `<iframe src="${url}" width="100%" height="700" frameborder="0" style="border:none"></iframe>`;
|
||||
}
|
||||
|
||||
export async function bookingPageEditorLoader({ request, params }: LoaderFunctionArgs) {
|
||||
const ctx = await loadBookingContext({ request, params, requireModule: true });
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const origin = new URL(request.url).origin;
|
||||
|
||||
const page = params.id ? await getBookingPageForEdit(ctx.tenantId, params.id) : null;
|
||||
if (params.id && !page) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
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 });
|
||||
}
|
||||
|
||||
export async function bookingPageEditorAction({ request, params }: ActionFunctionArgs) {
|
||||
const ctx = await loadBookingContext({ request, params, requireModule: true });
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const slug = ((form.get("slug") as string | null) ?? "").trim().toLowerCase();
|
||||
const title = ((form.get("title") as string | null) ?? "").trim();
|
||||
|
||||
if (!/^[a-z0-9-]{3,60}$/u.test(slug)) {
|
||||
return data<BookingPageEditorActionData>({ ok: false, errorKey: "bookings.error.slugReserved", field: "slug" }, { status: 400 });
|
||||
}
|
||||
if (RESERVED_BOOKING_SLUGS.has(slug)) {
|
||||
return data<BookingPageEditorActionData>({ ok: false, errorKey: "bookings.error.slugReserved", field: "slug" }, { status: 400 });
|
||||
}
|
||||
if (await isSlugTaken(ctx.tenantId, slug, params.id)) {
|
||||
return data<BookingPageEditorActionData>({ ok: false, errorKey: "bookings.error.slugTaken", field: "slug" }, { status: 409 });
|
||||
}
|
||||
|
||||
const providerUserIds = ((form.get("providers") as string | null) ?? "")
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
if (providerUserIds.length === 0) {
|
||||
return data<BookingPageEditorActionData>({ ok: false, errorKey: "bookings.error.providerRequired", field: "providers" }, { status: 400 });
|
||||
}
|
||||
|
||||
const input = {
|
||||
tenantId: ctx.tenantId,
|
||||
createdByUserId: ctx.userId,
|
||||
slug,
|
||||
title: title || slug,
|
||||
description: (form.get("description") as string | null) ?? null,
|
||||
durationMinutes: Number(form.get("durationMinutes")) || 30,
|
||||
confirmationEmailSubject: ((form.get("confirmationEmailSubject") as string | null) ?? "").trim() || `Bestätigung: ${title || slug}`,
|
||||
confirmationEmailBody: ((form.get("confirmationEmailBody") as string | null) ?? "").trim() || "Dein Termin ist bestätigt.",
|
||||
isPublished: form.get("isPublished") === "on" || form.get("isPublished") === "true",
|
||||
providerUserIds,
|
||||
};
|
||||
|
||||
if (params.id) {
|
||||
await updateBookingPage(params.id, input);
|
||||
} else {
|
||||
await createBookingPage(input);
|
||||
}
|
||||
return redirect(bookingPagesListPath(params.tenant ?? ""));
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
// AK-P16b · public booking flow (M06 Block G) — loader + action shared by the
|
||||
// canonical `/b/{tenant}/{slug}` route and its `/embed` iframe variant. NO auth, NO
|
||||
// session CSRF (there is no logged-in user); abuse is bounded by a honeypot + the
|
||||
// GDPR-acceptance gate + the slot re-check on submit. The tenant is resolved from
|
||||
// the URL slug; an unknown/inactive tenant or unpublished page is a 404 with the
|
||||
// same Klartext (never leaks tenant existence, M06 G.4/K.6).
|
||||
|
||||
import { type LoaderFunctionArgs, type ActionFunctionArgs, data, redirect } from "react-router";
|
||||
import { formatInTimeZone } from "date-fns-tz";
|
||||
import { notFoundResponse } from "./bookingRoutePaths";
|
||||
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";
|
||||
|
||||
const DEFAULT_TZ = "Europe/Berlin";
|
||||
|
||||
export interface PublicBookingSlotVM {
|
||||
readonly startAtIso: string;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
export interface PublicBookingLoaderData {
|
||||
readonly tenantSlug: string;
|
||||
readonly slug: string;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly tenantName: string;
|
||||
readonly durationMinutes: number;
|
||||
readonly date: string;
|
||||
readonly timezone: string;
|
||||
readonly slots: PublicBookingSlotVM[];
|
||||
readonly isEmbed: boolean;
|
||||
}
|
||||
|
||||
export type PublicBookingActionData =
|
||||
| { readonly ok: true; readonly titleLabel: string; readonly dateLabel: string; readonly timeLabel: string; readonly icsBase64: string }
|
||||
| { readonly ok: false; readonly errorKey: string; readonly field?: string };
|
||||
|
||||
function resolveTimezone(url: URL): string {
|
||||
return url.searchParams.get("tz") || DEFAULT_TZ;
|
||||
}
|
||||
|
||||
function resolveDate(url: URL, timezone: string, now: Date): string {
|
||||
const requested = url.searchParams.get("date");
|
||||
if (requested && /^\d{4}-\d{2}-\d{2}$/u.test(requested)) {
|
||||
return requested;
|
||||
}
|
||||
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[]> {
|
||||
const slots = await loadSlotsForDate({ tenantId, providerUserIds, date, config, now });
|
||||
return slots
|
||||
.filter((slot) => pickFirstAvailableProvider(slot) !== null)
|
||||
.map((slot) => ({ startAtIso: slot.startAt.toISOString(), label: formatInTimeZone(slot.startAt, timezone, "HH:mm") }));
|
||||
}
|
||||
|
||||
export async function publicBookingLoader({ request, params }: LoaderFunctionArgs) {
|
||||
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);
|
||||
}
|
||||
|
||||
export async function publicBookingAction({ request, params }: ActionFunctionArgs) {
|
||||
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 });
|
||||
}
|
||||
|
||||
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) ?? "";
|
||||
|
||||
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 });
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
// AK-P16b · static authorization-boundary guard for the booking mutation routes
|
||||
// (DoD A.5 / DoD 6). Asserts every state-changing action runs the module/permission
|
||||
// guard, the owner-check (where applicable) and CSRF validation BEFORE it reads the
|
||||
// form body — so a missing module/permission/owner/CSRF can never reach a mutation.
|
||||
|
||||
const appRoot = resolveRepoPath("apps/web/app");
|
||||
|
||||
describe("booking route authorization boundary", () => {
|
||||
test("appointment detail action guards permission + CSRF + owner before parsing the form", () => {
|
||||
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/bookings.$id.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)");
|
||||
const ownerAt = source.indexOf("requireAppointmentOwner(ctx, appt.providerUserId)", source.indexOf("export const action"));
|
||||
|
||||
expect(permissionAt).toBeGreaterThanOrEqual(0);
|
||||
expect(csrfAt).toBeGreaterThanOrEqual(0);
|
||||
expect(ownerAt).toBeGreaterThanOrEqual(0);
|
||||
expect(permissionAt).toBeLessThan(formDataAt);
|
||||
expect(csrfAt).toBeLessThan(formDataAt);
|
||||
expect(ownerAt).toBeLessThan(formDataAt);
|
||||
});
|
||||
|
||||
test("appointment detail mutation intents use write/admin permissions for lifecycle changes", () => {
|
||||
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/bookings.$id.tsx"), "utf8");
|
||||
|
||||
expect(source).toContain("rescheduleAppointment");
|
||||
expect(source).toContain("reassignAppointment");
|
||||
expect(source.match(/requireBookingPermission\(ctx, BOOKING_PERMISSIONS\.write\)/g)?.length ?? 0).toBeGreaterThanOrEqual(4);
|
||||
expect(source).toContain("requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin)");
|
||||
expect(source).toContain('intent === "reschedule"');
|
||||
expect(source).toContain('intent === "reassign"');
|
||||
});
|
||||
|
||||
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()");
|
||||
expect(formDataAt).toBeGreaterThanOrEqual(0);
|
||||
|
||||
const permissionAt = source.indexOf("requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin)", source.indexOf("bookingPageEditorAction"));
|
||||
const csrfAt = source.indexOf("await validateCSRFToken(request)");
|
||||
expect(permissionAt).toBeGreaterThanOrEqual(0);
|
||||
expect(csrfAt).toBeGreaterThanOrEqual(0);
|
||||
expect(permissionAt).toBeLessThan(formDataAt);
|
||||
expect(csrfAt).toBeLessThan(formDataAt);
|
||||
});
|
||||
});
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
// AK-P16b · shared loader/action guard for the booking module (mirrors
|
||||
// calendarAccess). Booking is feature-gated by its OWN `booking` key
|
||||
// (tenantHasModule, M06 DoD 7). The bookings.* bundle is cumulative (M06 Block K):
|
||||
// read_own < read_all < write < admin. Module-off 404s on write (Bauprinzip
|
||||
// A.5.3); a permission/owner miss is a 404, never a 403.
|
||||
//
|
||||
// The PUBLIC booking flow (/b/{tenant}/{slug}) does NOT use this guard — it resolves
|
||||
// the tenant from the URL segment and has no logged-in user (see the public route).
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { BOOKING_MODULE_KEY } from "./bookingRoutePaths";
|
||||
|
||||
/** Booking atomic permissions, cumulative bundle (M06 Block K). */
|
||||
export const BOOKING_PERMISSIONS = {
|
||||
/** See your OWN appointments + edit your OWN availability (default capability). */
|
||||
readOwn: "bookings.read_own",
|
||||
/** See all tenant appointments / pages / availability. */
|
||||
readAll: "bookings.read_all",
|
||||
/** Manage appointments (held/no_show/cancel/reschedule). */
|
||||
write: "bookings.write",
|
||||
/** Booking-page CRUD, foreign availability, provider re-assign, hard-delete. */
|
||||
admin: "bookings.admin",
|
||||
} as const;
|
||||
|
||||
export type BookingRouteContext = {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
permissions: readonly string[];
|
||||
hasModule: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve the booking route context: auth + tenant + the `booking` module gate +
|
||||
* the user's permissions. With `requireModule` a module-off tenant 404s (write
|
||||
* paths); GET paths can render a locked empty VM from `hasModule === false`.
|
||||
*/
|
||||
export async function loadBookingContext({
|
||||
request,
|
||||
params,
|
||||
requireModule = false,
|
||||
}: {
|
||||
request: Request;
|
||||
params: Record<string, string | undefined>;
|
||||
requireModule?: boolean;
|
||||
}): Promise<BookingRouteContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: BOOKING_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
]);
|
||||
if (requireModule && !hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: BOOKING_MODULE_KEY });
|
||||
}
|
||||
return { tenantId, userId: userInfo.userId, permissions, hasModule };
|
||||
}
|
||||
|
||||
/** True if the user holds `permission` or the broader `bookings.admin` bundle. */
|
||||
export function bookingHasPermission(ctx: BookingRouteContext, permission: string): boolean {
|
||||
return ctx.permissions.includes(permission) || ctx.permissions.includes(BOOKING_PERMISSIONS.admin);
|
||||
}
|
||||
|
||||
/** Require a bookings.* permission (admin-aware); 404 if missing (A.5.3). */
|
||||
export function requireBookingPermission(ctx: BookingRouteContext, permission: string): BookingRouteContext {
|
||||
if (!bookingHasPermission(ctx, permission)) {
|
||||
throw new CatalogError(foundationErrors.notFound, { permission });
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/** True if the user may see all appointments (read_all or admin), not just own. */
|
||||
export function canReadAllBookings(ctx: BookingRouteContext): boolean {
|
||||
return ctx.permissions.includes(BOOKING_PERMISSIONS.readAll) || ctx.permissions.includes(BOOKING_PERMISSIONS.admin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Owner-check for appointment-scoped routes (M06 K.5): a `read_own` user may only
|
||||
* see/act on appointments they hold (`providerUserId = self`) — UNLESS they hold
|
||||
* read_all/admin. A miss is a 404, not a 403 (A.5.3).
|
||||
*/
|
||||
export function requireAppointmentOwner(ctx: BookingRouteContext, providerUserId: string): BookingRouteContext {
|
||||
if (ctx.userId === providerUserId || canReadAllBookings(ctx)) {
|
||||
return ctx;
|
||||
}
|
||||
throw new CatalogError(foundationErrors.notFound, { owner: "mismatch" });
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
// AK-P16b · pure client-safe route-path builders for the booking module. Loaders
|
||||
// build these and pass them into the VMs so the VMs stay routing-agnostic (mirrors
|
||||
// calendarRoutePaths). The module is feature-gated by its OWN `booking` key
|
||||
// (tenantHasModule) — unlike calendar which reuses `integrations`.
|
||||
|
||||
/** Tenant-connector module key for the Booking feature (M06 / DoD 7). */
|
||||
export const BOOKING_MODULE_KEY = "booking";
|
||||
|
||||
/** Reserved slugs that may not be used for a public booking page. */
|
||||
export const RESERVED_BOOKING_SLUGS: ReadonlySet<string> = new Set([
|
||||
"new",
|
||||
"pages",
|
||||
"embed",
|
||||
"admin",
|
||||
"api",
|
||||
"settings",
|
||||
]);
|
||||
|
||||
/** Appointments list (M06 Block C). */
|
||||
export function bookingsListPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/bookings`;
|
||||
}
|
||||
|
||||
/** A single appointment's detail (M06 Block D). */
|
||||
export function bookingDetailPath(tenantSlug: string, appointmentId: string): string {
|
||||
return `/${tenantSlug}/bookings/${appointmentId}`;
|
||||
}
|
||||
|
||||
/** Booking-pages list (M06 Block E.1). */
|
||||
export function bookingPagesListPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/bookings/pages`;
|
||||
}
|
||||
|
||||
/** New booking-page editor (M06 Block E.2). */
|
||||
export function bookingPageNewPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/bookings/pages/new`;
|
||||
}
|
||||
|
||||
/** Edit an existing booking-page (M06 Block E.2). */
|
||||
export function bookingPageEditPath(tenantSlug: string, bookingPageId: string): string {
|
||||
return `/${tenantSlug}/bookings/pages/${bookingPageId}`;
|
||||
}
|
||||
|
||||
/** Per-user availability editor (M06 Block F). */
|
||||
export function availabilityPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/availability`;
|
||||
}
|
||||
|
||||
/** Public booking page (M06 Block G). NOT tenant-login-scoped. */
|
||||
export function publicBookingPath(tenantSlug: string, slug: string): string {
|
||||
return `/b/${tenantSlug}/${slug}`;
|
||||
}
|
||||
|
||||
/** Iframe embed variant of the public booking page (M06 Block H). */
|
||||
export function publicBookingEmbedPath(tenantSlug: string, slug: string): string {
|
||||
return `/b/${tenantSlug}/${slug}/embed`;
|
||||
}
|
||||
|
||||
/** Absolute public URL (for the editor's copy-to-clipboard + iframe snippet). */
|
||||
export function publicBookingUrl(origin: string, tenantSlug: string, slug: string): string {
|
||||
return `${origin}${publicBookingPath(tenantSlug, slug)}`;
|
||||
}
|
||||
|
||||
/** 404 helper (Bauprinzip A.5.3 — permission/owner miss renders 404, not 403). */
|
||||
export function notFoundResponse(): Response {
|
||||
return new Response("Not Found", { status: 404 });
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AvailabilityValidationError, listProviderAvailability, replaceProviderAvailability } from "./AvailabilityService.server";
|
||||
|
||||
const dbMock = vi.hoisted(() => ({
|
||||
availabilityRule: {
|
||||
findMany: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
createMany: vi.fn(),
|
||||
},
|
||||
availabilityException: {
|
||||
findMany: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
createMany: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
|
||||
|
||||
describe("AvailabilityService.server", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.$transaction.mockImplementation(async (fn: (tx: typeof dbMock) => Promise<unknown>) => fn(dbMock));
|
||||
});
|
||||
|
||||
it("loads and sorts provider availability", async () => {
|
||||
dbMock.availabilityRule.findMany.mockResolvedValue([
|
||||
{ id: "rule_2", dayOfWeek: "wednesday", startTime: "14:00", endTime: "17:00", timezone: "Europe/Berlin" },
|
||||
{ id: "rule_1", dayOfWeek: "monday", startTime: "09:00", endTime: "12:00", timezone: "Europe/Berlin" },
|
||||
]);
|
||||
dbMock.availabilityException.findMany.mockResolvedValue([
|
||||
{ id: "ex_2", date: new Date("2026-07-11T00:00:00Z"), kind: "custom_window", startTime: "10:00", endTime: "13:00", reason: "Workshop", timezone: "Europe/Berlin" },
|
||||
{ id: "ex_1", date: new Date("2026-07-10T00:00:00Z"), kind: "unavailable", startTime: null, endTime: null, reason: "Urlaub", timezone: "Europe/Berlin" },
|
||||
]);
|
||||
|
||||
await expect(listProviderAvailability("tenant_1", "user_1")).resolves.toEqual({
|
||||
providerUserId: "user_1",
|
||||
rules: [
|
||||
{ id: "rule_1", dayOfWeek: "monday", startTime: "09:00", endTime: "12:00", timezone: "Europe/Berlin" },
|
||||
{ id: "rule_2", dayOfWeek: "wednesday", startTime: "14:00", endTime: "17:00", timezone: "Europe/Berlin" },
|
||||
],
|
||||
exceptions: [
|
||||
{ id: "ex_1", date: "2026-07-10", kind: "unavailable", startTime: null, endTime: null, reason: "Urlaub", timezone: "Europe/Berlin" },
|
||||
{ id: "ex_2", date: "2026-07-11", kind: "custom_window", startTime: "10:00", endTime: "13:00", reason: "Workshop", timezone: "Europe/Berlin" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces rules and exceptions atomically with normalized values", async () => {
|
||||
await replaceProviderAvailability({
|
||||
tenantId: "tenant_1",
|
||||
providerUserId: "user_1",
|
||||
rules: [{ dayOfWeek: "monday", startTime: "09:00", endTime: "12:00", timezone: " Europe/Berlin " }],
|
||||
exceptions: [
|
||||
{ date: "2026-07-10", kind: "unavailable", startTime: "09:00", endTime: "10:00", reason: " Urlaub ", timezone: "Europe/Berlin" },
|
||||
{ date: "2026-07-11", kind: "custom_window", startTime: "10:00", endTime: "13:00", reason: null, timezone: "Europe/Berlin" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(dbMock.$transaction).toHaveBeenCalledOnce();
|
||||
expect(dbMock.availabilityRule.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", providerUserId: "user_1" } });
|
||||
expect(dbMock.availabilityException.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", providerUserId: "user_1" } });
|
||||
expect(dbMock.availabilityRule.createMany).toHaveBeenCalledWith({
|
||||
data: [{ tenantId: "tenant_1", providerUserId: "user_1", dayOfWeek: "monday", startTime: "09:00", endTime: "12:00", timezone: "Europe/Berlin" }],
|
||||
});
|
||||
expect(dbMock.availabilityException.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
{ tenantId: "tenant_1", providerUserId: "user_1", date: new Date("2026-07-10T00:00:00Z"), kind: "unavailable", startTime: null, endTime: null, reason: "Urlaub", timezone: "Europe/Berlin" },
|
||||
{ tenantId: "tenant_1", providerUserId: "user_1", date: new Date("2026-07-11T00:00:00Z"), kind: "custom_window", startTime: "10:00", endTime: "13:00", reason: null, timezone: "Europe/Berlin" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects invalid time windows before writing", async () => {
|
||||
await expect(
|
||||
replaceProviderAvailability({
|
||||
tenantId: "tenant_1",
|
||||
providerUserId: "user_1",
|
||||
rules: [{ dayOfWeek: "monday", startTime: "12:00", endTime: "09:00", timezone: "Europe/Berlin" }],
|
||||
exceptions: [],
|
||||
}),
|
||||
).rejects.toBeInstanceOf(AvailabilityValidationError);
|
||||
expect(dbMock.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires custom-window exception times before writing", async () => {
|
||||
await expect(
|
||||
replaceProviderAvailability({
|
||||
tenantId: "tenant_1",
|
||||
providerUserId: "user_1",
|
||||
rules: [],
|
||||
exceptions: [{ date: "2026-07-10", kind: "custom_window", timezone: "Europe/Berlin" }],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "bookings.error.invalidTimeWindow" });
|
||||
expect(dbMock.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
// AK-P16b · provider availability write/read service (M06 Block F). The screen is
|
||||
// still D-P16-blocked, but the server-side contract is complete: rules and date
|
||||
// exceptions are validated, tenant/provider-scoped, and replaced atomically.
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
import type { BookingWeekday } from "./slotEngine";
|
||||
|
||||
export type AvailabilityExceptionKind = "unavailable" | "custom_window";
|
||||
|
||||
export interface AvailabilityRuleInput {
|
||||
readonly dayOfWeek: BookingWeekday;
|
||||
readonly startTime: string;
|
||||
readonly endTime: string;
|
||||
readonly timezone: string;
|
||||
}
|
||||
|
||||
export interface AvailabilityExceptionInput {
|
||||
/** ISO calendar date `YYYY-MM-DD`. */
|
||||
readonly date: string;
|
||||
readonly kind: AvailabilityExceptionKind;
|
||||
readonly startTime?: string | null;
|
||||
readonly endTime?: string | null;
|
||||
readonly reason?: string | null;
|
||||
readonly timezone: string;
|
||||
}
|
||||
|
||||
export interface AvailabilityRuleRow extends AvailabilityRuleInput {
|
||||
readonly id: string;
|
||||
}
|
||||
|
||||
export interface AvailabilityExceptionRow {
|
||||
readonly id: string;
|
||||
readonly date: string;
|
||||
readonly kind: AvailabilityExceptionKind;
|
||||
readonly startTime: string | null;
|
||||
readonly endTime: string | null;
|
||||
readonly reason: string | null;
|
||||
readonly timezone: string;
|
||||
}
|
||||
|
||||
export interface ProviderAvailabilitySettings {
|
||||
readonly providerUserId: string;
|
||||
readonly rules: AvailabilityRuleRow[];
|
||||
readonly exceptions: AvailabilityExceptionRow[];
|
||||
}
|
||||
|
||||
export class AvailabilityValidationError extends Error {
|
||||
readonly code: string;
|
||||
constructor(code: string) {
|
||||
super(code);
|
||||
this.name = "AvailabilityValidationError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
const WEEKDAYS: readonly BookingWeekday[] = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
|
||||
const WEEKDAY_ORDER = new Map(WEEKDAYS.map((day, index) => [day, index]));
|
||||
const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/u;
|
||||
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/u;
|
||||
|
||||
function assertTimezone(timezone: string): void {
|
||||
try {
|
||||
new Intl.DateTimeFormat("en", { timeZone: timezone }).format(new Date("2026-01-01T00:00:00Z"));
|
||||
} catch {
|
||||
throw new AvailabilityValidationError("bookings.error.invalidTimezone");
|
||||
}
|
||||
}
|
||||
|
||||
function minutesOf(time: string): number {
|
||||
if (!TIME_RE.test(time)) {
|
||||
throw new AvailabilityValidationError("bookings.error.invalidTime");
|
||||
}
|
||||
const [hours, minutes] = time.split(":").map(Number);
|
||||
return hours * 60 + minutes;
|
||||
}
|
||||
|
||||
function isoDateToDbDate(date: string): Date {
|
||||
if (!DATE_RE.test(date)) {
|
||||
throw new AvailabilityValidationError("bookings.error.invalidDate");
|
||||
}
|
||||
return new Date(`${date}T00:00:00Z`);
|
||||
}
|
||||
|
||||
function dbDateToIso(date: Date): string {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function validateWindow(startTime: string, endTime: string): void {
|
||||
if (minutesOf(endTime) <= minutesOf(startTime)) {
|
||||
throw new AvailabilityValidationError("bookings.error.invalidTimeWindow");
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRule(rule: AvailabilityRuleInput): AvailabilityRuleInput {
|
||||
if (!WEEKDAY_ORDER.has(rule.dayOfWeek)) {
|
||||
throw new AvailabilityValidationError("bookings.error.invalidWeekday");
|
||||
}
|
||||
const timezone = rule.timezone.trim();
|
||||
assertTimezone(timezone);
|
||||
validateWindow(rule.startTime, rule.endTime);
|
||||
return { dayOfWeek: rule.dayOfWeek, startTime: rule.startTime, endTime: rule.endTime, timezone };
|
||||
}
|
||||
|
||||
function normalizeException(exception: AvailabilityExceptionInput): AvailabilityExceptionInput & { dateObject: Date } {
|
||||
if (exception.kind !== "unavailable" && exception.kind !== "custom_window") {
|
||||
throw new AvailabilityValidationError("bookings.error.invalidAvailabilityException");
|
||||
}
|
||||
const timezone = exception.timezone.trim();
|
||||
assertTimezone(timezone);
|
||||
const dateObject = isoDateToDbDate(exception.date);
|
||||
if (exception.kind === "custom_window") {
|
||||
if (!exception.startTime || !exception.endTime) {
|
||||
throw new AvailabilityValidationError("bookings.error.invalidTimeWindow");
|
||||
}
|
||||
validateWindow(exception.startTime, exception.endTime);
|
||||
return {
|
||||
...exception,
|
||||
dateObject,
|
||||
timezone,
|
||||
startTime: exception.startTime,
|
||||
endTime: exception.endTime,
|
||||
reason: exception.reason?.trim() || null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...exception,
|
||||
dateObject,
|
||||
timezone,
|
||||
startTime: null,
|
||||
endTime: null,
|
||||
reason: exception.reason?.trim() || null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Load one provider's persisted availability settings. */
|
||||
export async function listProviderAvailability(tenantId: string, providerUserId: string): Promise<ProviderAvailabilitySettings> {
|
||||
const [rules, exceptions] = await Promise.all([
|
||||
db.availabilityRule.findMany({
|
||||
where: { tenantId, providerUserId },
|
||||
select: { id: true, dayOfWeek: true, startTime: true, endTime: true, timezone: true },
|
||||
}),
|
||||
db.availabilityException.findMany({
|
||||
where: { tenantId, providerUserId },
|
||||
select: { id: true, date: true, kind: true, startTime: true, endTime: true, reason: true, timezone: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
providerUserId,
|
||||
rules: rules
|
||||
.map((rule) => ({ id: rule.id, dayOfWeek: rule.dayOfWeek as BookingWeekday, startTime: rule.startTime, endTime: rule.endTime, timezone: rule.timezone }))
|
||||
.sort((a, b) => (WEEKDAY_ORDER.get(a.dayOfWeek) ?? 99) - (WEEKDAY_ORDER.get(b.dayOfWeek) ?? 99) || a.startTime.localeCompare(b.startTime)),
|
||||
exceptions: exceptions
|
||||
.map((exception) => ({
|
||||
id: exception.id,
|
||||
date: dbDateToIso(exception.date),
|
||||
kind: exception.kind as AvailabilityExceptionKind,
|
||||
startTime: exception.startTime,
|
||||
endTime: exception.endTime,
|
||||
reason: exception.reason,
|
||||
timezone: exception.timezone,
|
||||
}))
|
||||
.sort((a, b) => a.date.localeCompare(b.date) || (a.startTime ?? "").localeCompare(b.startTime ?? "")),
|
||||
};
|
||||
}
|
||||
|
||||
/** Replace a provider's availability settings atomically. */
|
||||
export async function replaceProviderAvailability(input: {
|
||||
readonly tenantId: string;
|
||||
readonly providerUserId: string;
|
||||
readonly rules: readonly AvailabilityRuleInput[];
|
||||
readonly exceptions: readonly AvailabilityExceptionInput[];
|
||||
}): Promise<void> {
|
||||
const rules = input.rules.map(normalizeRule);
|
||||
const exceptions = input.exceptions.map(normalizeException);
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.availabilityRule.deleteMany({ where: { tenantId: input.tenantId, providerUserId: input.providerUserId } });
|
||||
await tx.availabilityException.deleteMany({ where: { tenantId: input.tenantId, providerUserId: input.providerUserId } });
|
||||
if (rules.length > 0) {
|
||||
await tx.availabilityRule.createMany({
|
||||
data: rules.map((rule) => ({
|
||||
tenantId: input.tenantId,
|
||||
providerUserId: input.providerUserId,
|
||||
dayOfWeek: rule.dayOfWeek,
|
||||
startTime: rule.startTime,
|
||||
endTime: rule.endTime,
|
||||
timezone: rule.timezone,
|
||||
})),
|
||||
});
|
||||
}
|
||||
if (exceptions.length > 0) {
|
||||
await tx.availabilityException.createMany({
|
||||
data: exceptions.map((exception) => ({
|
||||
tenantId: input.tenantId,
|
||||
providerUserId: input.providerUserId,
|
||||
date: exception.dateObject,
|
||||
kind: exception.kind,
|
||||
startTime: exception.startTime,
|
||||
endTime: exception.endTime,
|
||||
reason: exception.reason ?? null,
|
||||
timezone: exception.timezone,
|
||||
})),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
// AK-P16b · appointment lifecycle (M06 Block D / M129 VOLL): held / no-show / cancel
|
||||
// / reschedule / re-assign. Transitions are validated by the pure state machine; the
|
||||
// local CalendarEvent mirror is kept in sync (archived on cancel, moved on re-assign,
|
||||
// superseded on reschedule). Customer-facing changes (cancel/reschedule/re-assign)
|
||||
// send an auto-mail (best-effort, M06 I.3) and record an Activity (M06 J.4); an in-app
|
||||
// notification goes to the provider via notify() (M011). External calendar push lands
|
||||
// with the AK-P16a write-path (here only the local mirror is updated).
|
||||
|
||||
import { formatInTimeZone } from "date-fns-tz";
|
||||
import { logActivity, type ActivityType } from "@hivegrid/activity";
|
||||
import { notify, type NotificationClient } from "@hivegrid/foundation";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
|
||||
import { assertTransition, statusAfter, notifiesCustomer, type LifecycleAction } from "./bookingTransitions";
|
||||
|
||||
const MINUTE_MS = 60_000;
|
||||
|
||||
interface AppointmentForAction {
|
||||
id: string;
|
||||
status: "scheduled" | "held" | "cancelled" | "no_show" | "rescheduled";
|
||||
providerUserId: string;
|
||||
bookingPageId: string;
|
||||
kontaktId: string | null;
|
||||
startAt: Date;
|
||||
endAt: Date;
|
||||
timezone: string;
|
||||
internalCalendarEventId: string | null;
|
||||
intakeAnswers: unknown;
|
||||
pageTitle: string;
|
||||
durationMinutes: number;
|
||||
tenantName: string;
|
||||
}
|
||||
|
||||
async function loadAppointmentForAction(tenantId: string, appointmentId: string): Promise<AppointmentForAction | null> {
|
||||
const row = await db.appointment.findFirst({
|
||||
where: { id: appointmentId, tenantId },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
providerUserId: true,
|
||||
bookingPageId: true,
|
||||
kontaktId: true,
|
||||
startAt: true,
|
||||
endAt: true,
|
||||
timezone: true,
|
||||
internalCalendarEventId: true,
|
||||
intakeAnswers: true,
|
||||
bookingPage: { select: { title: true, durationMinutes: true } },
|
||||
},
|
||||
});
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
const tenant = await db.tenant.findUnique({ where: { id: tenantId }, select: { name: true } });
|
||||
return {
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
providerUserId: row.providerUserId,
|
||||
bookingPageId: row.bookingPageId,
|
||||
kontaktId: row.kontaktId,
|
||||
startAt: row.startAt,
|
||||
endAt: row.endAt,
|
||||
timezone: row.timezone,
|
||||
internalCalendarEventId: row.internalCalendarEventId,
|
||||
intakeAnswers: row.intakeAnswers,
|
||||
pageTitle: row.bookingPage.title,
|
||||
durationMinutes: row.bookingPage.durationMinutes,
|
||||
tenantName: tenant?.name ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function bookerEmail(intakeAnswers: unknown): string | null {
|
||||
if (intakeAnswers && typeof intakeAnswers === "object" && "email" in intakeAnswers) {
|
||||
const email = (intakeAnswers as { email?: unknown }).email;
|
||||
return typeof email === "string" && email.trim() ? email.trim() : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function recordActivity(tenantId: string, appt: AppointmentForAction, activityType: ActivityType, summaryText: string, actorUserId: string | null): Promise<void> {
|
||||
if (!appt.kontaktId) {
|
||||
return;
|
||||
}
|
||||
await logActivity({
|
||||
tenantId,
|
||||
actorUserId,
|
||||
actorKind: actorUserId ? "user" : "system",
|
||||
activityType,
|
||||
subjectType: "contact",
|
||||
subjectId: appt.kontaktId,
|
||||
summaryText,
|
||||
metadata: { appointmentId: appt.id },
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
|
||||
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 } },
|
||||
db as unknown as NotificationClient
|
||||
).catch(() => undefined);
|
||||
}
|
||||
|
||||
async function sendLifecycleMail(appt: AppointmentForAction, subject: string, body: 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/>") } });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
/** 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");
|
||||
}
|
||||
|
||||
async function applyStatusOnly(tenantId: string, appointmentId: string, action: LifecycleAction, actorUserId: string, activityType: ActivityType, summaryVerb: string): Promise<void> {
|
||||
const appt = await loadAppointmentForAction(tenantId, appointmentId);
|
||||
if (!appt) {
|
||||
return;
|
||||
}
|
||||
assertTransition(appt.status, action);
|
||||
const next = statusAfter(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);
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
|
||||
if (!appt) {
|
||||
return;
|
||||
}
|
||||
assertTransition(appt.status, "cancel");
|
||||
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 },
|
||||
});
|
||||
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 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);
|
||||
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 }> {
|
||||
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
|
||||
if (!appt) {
|
||||
throw new Error("appointment_not_found");
|
||||
}
|
||||
assertTransition(appt.status, "reschedule");
|
||||
const newEndAt = new Date(input.newStartAt.getTime() + appt.durationMinutes * MINUTE_MS);
|
||||
|
||||
const newAppointmentId = await db.$transaction(async (tx) => {
|
||||
await tx.appointment.update({ where: { id: appt.id }, data: { status: "rescheduled" } });
|
||||
if (appt.internalCalendarEventId) {
|
||||
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { archivedAt: new Date(), isBusyForAvailability: false } });
|
||||
}
|
||||
const successor = await tx.appointment.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
bookingPageId: appt.bookingPageId,
|
||||
providerUserId: appt.providerUserId,
|
||||
startAt: input.newStartAt,
|
||||
endAt: newEndAt,
|
||||
timezone: appt.timezone,
|
||||
status: "scheduled",
|
||||
kontaktId: appt.kontaktId,
|
||||
intakeAnswers: appt.intakeAnswers as object,
|
||||
rescheduledFromId: appt.id,
|
||||
},
|
||||
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 } },
|
||||
select: { id: true },
|
||||
});
|
||||
await tx.appointment.update({ where: { id: successor.id }, data: { internalCalendarEventId: calendarEvent.id } });
|
||||
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 notifyProvider(input.tenantId, appt.providerUserId, "bookings.status.rescheduled", newAppointmentId);
|
||||
return { newAppointmentId };
|
||||
}
|
||||
|
||||
/** Re-assign the appointment to a different provider (M06 D, bookings.admin). */
|
||||
export async function reassignAppointment(input: { tenantId: string; appointmentId: string; newProviderUserId: string; actorUserId: string }): Promise<void> {
|
||||
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
|
||||
if (!appt) {
|
||||
return;
|
||||
}
|
||||
assertTransition(appt.status, "reassign");
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.appointment.update({ where: { id: appt.id }, data: { providerUserId: input.newProviderUserId } });
|
||||
if (appt.internalCalendarEventId) {
|
||||
// Move the local mirror to the new provider so availability follows.
|
||||
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 notifyProvider(input.tenantId, input.newProviderUserId, "bookings.status.scheduled", appt.id);
|
||||
}
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
// AK-P16b · public booking submit (race-safe) + post-booking wiring (M06 G/I/J).
|
||||
//
|
||||
// Race protection is two-layered (DoD 2): (1) a Serializable transaction re-checks
|
||||
// slot freshness and inserts the appointment; (2) the PostgreSQL EXCLUDE USING gist
|
||||
// constraint `appointment_no_overlap` is the hard backstop — a lost race surfaces as
|
||||
// an exclusion violation that we map to the same Klartext "slot just taken".
|
||||
//
|
||||
// Post-booking (M06 J): email-match → existing Kontakt + Activity, otherwise a
|
||||
// typed InboxLead (R-P7) is created and linked via Appointment.leadId. The v1 mini
|
||||
// form remains in intakeAnswers and, when the booking page references an intake
|
||||
// form, is mirrored to FormSubmission + Appointment.formSubmissionId; a local
|
||||
// CalendarEvent blocks availability; confirmation mail carries an .ics attachment.
|
||||
|
||||
import { formatInTimeZone } from "date-fns-tz";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { createLead } from "~/utils/integrations/leads/leadService.server";
|
||||
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
|
||||
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";
|
||||
|
||||
const MINUTE_MS = 60_000;
|
||||
|
||||
export class BookingValidationError extends Error {
|
||||
readonly code: string;
|
||||
readonly field?: string;
|
||||
constructor(code: string, field?: string) {
|
||||
super(code);
|
||||
this.name = "BookingValidationError";
|
||||
this.code = code;
|
||||
this.field = field;
|
||||
}
|
||||
}
|
||||
|
||||
export class BookingSlotTakenError extends Error {
|
||||
readonly code = "slot_taken";
|
||||
constructor() {
|
||||
super("slot_taken");
|
||||
this.name = "BookingSlotTakenError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface BookingIntake {
|
||||
readonly vorname: string;
|
||||
readonly nachname: string;
|
||||
readonly email: string;
|
||||
readonly telefon?: string;
|
||||
readonly gdprAccepted: boolean;
|
||||
}
|
||||
|
||||
export interface BookingSubmitInput {
|
||||
readonly page: PublicBookingPage;
|
||||
/** Chosen slot start as a UTC ISO string. */
|
||||
readonly startAtIso: string;
|
||||
/** Provider-local date `YYYY-MM-DD` the slot belongs to. */
|
||||
readonly date: string;
|
||||
/** Booker's IANA timezone (for display + the appointment record). */
|
||||
readonly viewerTimeZone: string;
|
||||
readonly intake: BookingIntake;
|
||||
readonly now: Date;
|
||||
}
|
||||
|
||||
export interface BookingSubmitResult {
|
||||
readonly appointmentId: string;
|
||||
readonly providerUserId: string;
|
||||
readonly startAt: Date;
|
||||
readonly endAt: Date;
|
||||
readonly icsBase64: string;
|
||||
readonly redirectUrl: string | null;
|
||||
}
|
||||
|
||||
function validateIntake(intake: BookingIntake): void {
|
||||
if (!intake.vorname.trim()) {
|
||||
throw new BookingValidationError("bookings.error.firstNameRequired", "vorname");
|
||||
}
|
||||
if (!intake.nachname.trim()) {
|
||||
throw new BookingValidationError("bookings.error.lastNameRequired", "nachname");
|
||||
}
|
||||
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/u.test(intake.email.trim())) {
|
||||
throw new BookingValidationError("bookings.error.emailInvalid", "email");
|
||||
}
|
||||
if (!intake.gdprAccepted) {
|
||||
throw new BookingValidationError("bookings.error.gdprRequired", "gdpr");
|
||||
}
|
||||
}
|
||||
|
||||
/** Heuristic: a lost-race insert trips the gist exclusion constraint. */
|
||||
function isOverlapViolation(error: unknown): boolean {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return message.includes("appointment_no_overlap") || message.includes("23P01") || message.toLowerCase().includes("exclusion");
|
||||
}
|
||||
|
||||
function renderTemplate(template: string, vars: Record<string, string>): string {
|
||||
return template.replace(/\{\{\s*([\w.]+)\s*\}\}/gu, (_match, key: string) => vars[key] ?? "");
|
||||
}
|
||||
|
||||
/** Submit a public booking. Throws BookingValidationError / BookingSlotTakenError. */
|
||||
export async function submitBooking(input: BookingSubmitInput): Promise<BookingSubmitResult> {
|
||||
validateIntake(input.intake);
|
||||
const { page } = input;
|
||||
|
||||
// 1) Re-check the slot against live availability (M06 G.3).
|
||||
const slots = await loadSlotsForDate({
|
||||
tenantId: page.tenantId,
|
||||
providerUserIds: page.providerUserIds,
|
||||
date: input.date,
|
||||
config: page.config,
|
||||
now: input.now,
|
||||
});
|
||||
const slot = slots.find((s) => s.startAt.toISOString() === new Date(input.startAtIso).toISOString());
|
||||
const providerUserId = slot ? pickFirstAvailableProvider(slot) : null;
|
||||
if (!slot || !providerUserId) {
|
||||
throw new BookingSlotTakenError();
|
||||
}
|
||||
const startAt = slot.startAt;
|
||||
const endAt = new Date(startAt.getTime() + page.durationMinutes * MINUTE_MS);
|
||||
|
||||
// 2) Match an existing contact; otherwise create a typed InboxLead after the
|
||||
// appointment exists so the lead can reference the booked appointment id.
|
||||
const kontaktId = await findKontaktIdByEmail(page.tenantId, input.intake.email);
|
||||
let leadId: string | null = null;
|
||||
|
||||
const intakeAnswers = {
|
||||
vorname: input.intake.vorname.trim(),
|
||||
nachname: input.intake.nachname.trim(),
|
||||
email: input.intake.email.trim(),
|
||||
telefon: input.intake.telefon?.trim() ?? null,
|
||||
gdprAccepted: true,
|
||||
};
|
||||
const eventTitle = renderTemplate(page.internalEventTitleTemplate ?? "{{booking_page.title}}", {
|
||||
"booking_page.title": page.title,
|
||||
"contact.name": `${input.intake.vorname} ${input.intake.nachname}`.trim(),
|
||||
});
|
||||
|
||||
// 3) Race-safe insert: Serializable re-check + gist backstop (DoD 2).
|
||||
let appointmentId: string;
|
||||
try {
|
||||
appointmentId = await db.$transaction(
|
||||
async (tx) => {
|
||||
const clash = await tx.appointment.findFirst({
|
||||
where: {
|
||||
tenantId: page.tenantId,
|
||||
providerUserId,
|
||||
status: { in: ["scheduled", "held"] },
|
||||
AND: [{ startAt: { lt: endAt } }, { endAt: { gt: startAt } }],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (clash) {
|
||||
throw new BookingSlotTakenError();
|
||||
}
|
||||
const appointment = await tx.appointment.create({
|
||||
data: {
|
||||
tenantId: page.tenantId,
|
||||
bookingPageId: page.pageId,
|
||||
providerUserId,
|
||||
startAt,
|
||||
endAt,
|
||||
timezone: input.viewerTimeZone,
|
||||
status: "scheduled",
|
||||
kontaktId,
|
||||
intakeAnswers,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
const formSubmission = page.intakeFormId
|
||||
? await tx.formSubmission.create({
|
||||
data: {
|
||||
formId: page.intakeFormId,
|
||||
tenantId: page.tenantId,
|
||||
payload: {
|
||||
values: intakeAnswers,
|
||||
booking: {
|
||||
appointmentId: appointment.id,
|
||||
bookingPageId: page.pageId,
|
||||
bookingPageSlug: page.slug,
|
||||
startAt: startAt.toISOString(),
|
||||
endAt: endAt.toISOString(),
|
||||
},
|
||||
},
|
||||
sourceOrigin: `/b/${page.tenantSlug}/${page.slug}`,
|
||||
status: "received",
|
||||
result: { target: "booking_intake" },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
: null;
|
||||
// Local calendar mirror so the slot blocks future availability (M06 J.2).
|
||||
const calendarEvent = await tx.calendarEvent.create({
|
||||
data: {
|
||||
tenantId: page.tenantId,
|
||||
userId: providerUserId,
|
||||
source: "hivegrid_internal",
|
||||
title: eventTitle,
|
||||
startsAt: startAt,
|
||||
endsAt: endAt,
|
||||
isBusyForAvailability: true,
|
||||
internalEntityLink: { type: "booking_appointment", id: appointment.id },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
await tx.appointment.update({
|
||||
where: { id: appointment.id },
|
||||
data: { internalCalendarEventId: calendarEvent.id, formSubmissionId: formSubmission?.id ?? null },
|
||||
});
|
||||
return appointment.id;
|
||||
},
|
||||
{ isolationLevel: "Serializable" }
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof BookingSlotTakenError || isOverlapViolation(error)) {
|
||||
throw new BookingSlotTakenError();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!kontaktId) {
|
||||
const lead = await createLead({
|
||||
tenantId: page.tenantId,
|
||||
userId: null,
|
||||
quelle: "form",
|
||||
quelleDetail: { kind: "booking", bookingPageId: page.pageId, bookingPageSlug: page.slug },
|
||||
sourceOrigin: `/b/${page.tenantSlug}/${page.slug}`,
|
||||
vorname: input.intake.vorname,
|
||||
nachname: input.intake.nachname,
|
||||
email: input.intake.email,
|
||||
telefon: input.intake.telefon,
|
||||
message: page.title,
|
||||
rohdaten: { bookingPageId: page.pageId, appointmentId, startAt: startAt.toISOString(), endAt: endAt.toISOString(), intakeAnswers },
|
||||
zustaendigerUserId: providerUserId,
|
||||
weiterverarbeitungFreigabe: "unklar",
|
||||
});
|
||||
leadId = lead.id;
|
||||
await db.appointment.update({ where: { id: appointmentId }, data: { leadId } });
|
||||
}
|
||||
|
||||
// 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;
|
||||
if (activitySubject) {
|
||||
await logActivity({
|
||||
tenantId: page.tenantId,
|
||||
actorUserId: null,
|
||||
actorKind: "system",
|
||||
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 },
|
||||
}).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.` } })
|
||||
.catch(() => undefined);
|
||||
return buildBookingIcs({ input, providerUserId, startAt, endAt, appointmentId });
|
||||
});
|
||||
|
||||
return { appointmentId, providerUserId, startAt, endAt, icsBase64, redirectUrl: page.redirectUrlAfterBooking };
|
||||
}
|
||||
|
||||
function buildBookingIcs(args: { input: BookingSubmitInput; providerUserId: string; startAt: Date; endAt: Date; appointmentId: string }): string {
|
||||
const { input, startAt, endAt, appointmentId } = args;
|
||||
const ics = buildIcs({
|
||||
uid: `${appointmentId}@hivegrid`,
|
||||
start: startAt,
|
||||
end: endAt,
|
||||
dtstamp: input.now,
|
||||
summary: input.page.title,
|
||||
description: input.page.description ?? undefined,
|
||||
organizerEmail: undefined,
|
||||
organizerName: input.page.tenantName,
|
||||
attendeeEmail: input.intake.email.trim(),
|
||||
});
|
||||
return icsToBase64(ics);
|
||||
}
|
||||
|
||||
async function sendConfirmation(args: { input: BookingSubmitInput; providerUserId: string; startAt: Date; endAt: Date; appointmentId: string }): Promise<string> {
|
||||
const { input, startAt, endAt } = args;
|
||||
const { page } = input;
|
||||
const icsBase64 = buildBookingIcs(args);
|
||||
|
||||
const vars: Record<string, string> = {
|
||||
"contact.first_name": input.intake.vorname.trim(),
|
||||
"contact.last_name": input.intake.nachname.trim(),
|
||||
"contact.email": input.intake.email.trim(),
|
||||
"booking_page.title": page.title,
|
||||
"booking_page.description": page.description ?? "",
|
||||
"booking_page.duration_minutes": String(page.durationMinutes),
|
||||
"appointment.date": formatInTimeZone(startAt, input.viewerTimeZone, "dd.MM.yyyy"),
|
||||
"appointment.time": formatInTimeZone(startAt, input.viewerTimeZone, "HH:mm"),
|
||||
"appointment.duration": String(page.durationMinutes),
|
||||
"tenant.company_name": page.tenantName,
|
||||
};
|
||||
const subject = renderTemplate(page.confirmationEmailSubject, vars);
|
||||
const body = renderTemplate(page.confirmationEmailBody, vars);
|
||||
|
||||
await sendEmailMailjet({
|
||||
data: {
|
||||
to: input.intake.email.trim(),
|
||||
subject,
|
||||
body: body.replace(/\r?\n/gu, "<br/>"),
|
||||
tenantId: page.tenantId,
|
||||
attachments: [{ filename: "termin.ics", content: icsBase64, disposition: "attachment" }],
|
||||
},
|
||||
});
|
||||
return icsBase64;
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
// AK-P16b · slot query service (loader-side). Loads availability rules, exceptions,
|
||||
// existing appointments and Google busy intervals (AK-P16a) for a booking page's
|
||||
// providers, then delegates the timezone-aware arithmetic to the pure slotEngine.
|
||||
//
|
||||
// Busy intervals fed to the engine combine, per provider:
|
||||
// - existing appointments (status scheduled/held) → [startAt, endAt)
|
||||
// - external/internal calendar events flagged busy → via availability.ts (leak-safe)
|
||||
// The engine buffers the candidate slot, so raw occupied intervals are enough.
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
import { extractBusyIntervals, type BusyInterval } from "~/modules/calendar/services/availability";
|
||||
import {
|
||||
computeSlots,
|
||||
type BookingWeekday,
|
||||
type ComputedSlot,
|
||||
type ProviderAvailabilityInput,
|
||||
type SlotEngineConfig,
|
||||
type SlotExceptionInput,
|
||||
type SlotRuleInput,
|
||||
} from "./slotEngine";
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const OCCUPYING_STATUSES = ["scheduled", "held"] as const;
|
||||
|
||||
export interface SlotQueryInput {
|
||||
readonly tenantId: string;
|
||||
readonly providerUserIds: readonly string[];
|
||||
/** Provider-local calendar date `YYYY-MM-DD`. */
|
||||
readonly date: string;
|
||||
readonly config: SlotEngineConfig;
|
||||
readonly now: Date;
|
||||
}
|
||||
|
||||
/** Broad UTC window around the requested local day (covers any provider timezone). */
|
||||
function dayWindow(date: string): { from: Date; to: Date } {
|
||||
const midnightUtc = new Date(`${date}T00:00:00Z`).getTime();
|
||||
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> {
|
||||
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 },
|
||||
}),
|
||||
db.availabilityException.findMany({
|
||||
where: { tenantId, providerUserId, date: new Date(`${date}T00:00:00Z`) },
|
||||
select: { 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 },
|
||||
}),
|
||||
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 },
|
||||
}),
|
||||
]);
|
||||
|
||||
const appointmentBusy: BusyInterval[] = appointments.map((a) => ({ from: a.startAt, to: a.endAt }));
|
||||
const calendarBusy = extractBusyIntervals(events);
|
||||
|
||||
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],
|
||||
};
|
||||
}
|
||||
|
||||
/** Compute the bookable slots for a booking page's providers on a given local day. */
|
||||
export async function loadSlotsForDate(input: SlotQueryInput): Promise<ComputedSlot[]> {
|
||||
if (input.providerUserIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const providers = await Promise.all(input.providerUserIds.map((id) => loadProviderInput(input.tenantId, id, input.date)));
|
||||
return computeSlots({ date: input.date, now: input.now, providers, config: input.config });
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
const repoRoot = resolveRepoPath(".");
|
||||
|
||||
function readArtifact(relativePath: string): string {
|
||||
return fs.readFileSync(path.join(repoRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
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");
|
||||
|
||||
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");
|
||||
});
|
||||
|
||||
test("booking RLS artifact covers every tenant-scoped booking table and fails closed without tenant GUC", () => {
|
||||
const sql = readArtifact("prisma/rls/booking-isolation.sql");
|
||||
const expectedTables = ["BookingPage", "BookingPageProvider", "AvailabilityRule", "AvailabilityException", "Appointment"];
|
||||
|
||||
for (const table of expectedTables) {
|
||||
expect(sql).toContain(`'${table}'`);
|
||||
}
|
||||
expect(sql).toContain("ENABLE ROW LEVEL SECURITY");
|
||||
expect(sql).toContain("FORCE ROW LEVEL SECURITY");
|
||||
expect(sql).toContain('"tenantId" = current_setting(\'\'app.tenant_id\'\', true)');
|
||||
expect(sql).toContain("GRANT SELECT, INSERT, UPDATE, DELETE");
|
||||
expect(sql).toContain("hivegrid_app");
|
||||
});
|
||||
});
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
const servicePath = path.join(resolveRepoPath("apps/web/app"), "modules/booking/services/BookingSubmitService.server.ts");
|
||||
|
||||
describe("booking post-booking server wiring", () => {
|
||||
test("public booking creates and links a typed InboxLead when no contact matches", () => {
|
||||
const source = fs.readFileSync(servicePath, "utf8");
|
||||
|
||||
expect(source).toContain('import { createLead } from "~/utils/integrations/leads/leadService.server"');
|
||||
expect(source).toContain("if (!kontaktId)");
|
||||
expect(source).toContain("const lead = await createLead");
|
||||
expect(source).toContain('quelle: "form"');
|
||||
expect(source).toContain('kind: "booking"');
|
||||
expect(source).toContain("appointmentId");
|
||||
expect(source).toContain("data: { leadId }");
|
||||
expect(source).toContain('type: "lead" as const');
|
||||
});
|
||||
|
||||
test("public booking persists a FormSubmission when an intake form is configured", () => {
|
||||
const source = fs.readFileSync(servicePath, "utf8");
|
||||
|
||||
expect(source).toContain("page.intakeFormId");
|
||||
expect(source).toContain("tx.formSubmission.create");
|
||||
expect(source).toContain("formId: page.intakeFormId");
|
||||
expect(source).toContain("formSubmissionId: formSubmission?.id ?? null");
|
||||
expect(source).toContain('target: "booking_intake"');
|
||||
});
|
||||
});
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
assertTransition,
|
||||
BookingTransitionError,
|
||||
canTransition,
|
||||
notifiesCustomer,
|
||||
statusAfter,
|
||||
type AppointmentStatus,
|
||||
type LifecycleAction,
|
||||
} from "./bookingTransitions";
|
||||
|
||||
const ACTIONS: LifecycleAction[] = ["mark_held", "mark_no_show", "cancel", "reschedule", "reassign"];
|
||||
const TERMINAL: AppointmentStatus[] = ["held", "cancelled", "no_show", "rescheduled"];
|
||||
|
||||
describe("booking lifecycle transitions (M06 A.5 / M129)", () => {
|
||||
it("allows every action from scheduled", () => {
|
||||
for (const action of ACTIONS) {
|
||||
expect(canTransition("scheduled", action)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("forbids every action from a terminal status", () => {
|
||||
for (const status of TERMINAL) {
|
||||
for (const action of ACTIONS) {
|
||||
expect(canTransition(status, action)).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("assertTransition throws BookingTransitionError on an invalid transition", () => {
|
||||
expect(() => assertTransition("cancelled", "cancel")).toThrow(BookingTransitionError);
|
||||
expect(() => assertTransition("scheduled", "cancel")).not.toThrow();
|
||||
});
|
||||
|
||||
it("maps actions to the resulting status (reassign keeps it unchanged)", () => {
|
||||
expect(statusAfter("mark_held")).toBe("held");
|
||||
expect(statusAfter("mark_no_show")).toBe("no_show");
|
||||
expect(statusAfter("cancel")).toBe("cancelled");
|
||||
expect(statusAfter("reschedule")).toBe("rescheduled");
|
||||
expect(statusAfter("reassign")).toBeNull();
|
||||
});
|
||||
|
||||
it("flags customer-notifying actions (cancel/reschedule/reassign)", () => {
|
||||
expect(notifiesCustomer("cancel")).toBe(true);
|
||||
expect(notifiesCustomer("reschedule")).toBe(true);
|
||||
expect(notifiesCustomer("reassign")).toBe(true);
|
||||
expect(notifiesCustomer("mark_held")).toBe(false);
|
||||
expect(notifiesCustomer("mark_no_show")).toBe(false);
|
||||
});
|
||||
});
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// AK-P16b · appointment lifecycle state machine (PURE, M06 A.5 / M129). The allowed
|
||||
// transitions are validated here so the service + tests share one source of truth.
|
||||
//
|
||||
// scheduled ──mark_held──▶ held
|
||||
// scheduled ──mark_no_show──▶ no_show
|
||||
// scheduled ──cancel──▶ cancelled
|
||||
// scheduled ──reschedule──▶ rescheduled (a successor appointment is created)
|
||||
// scheduled ──reassign──▶ scheduled (provider changes, status unchanged)
|
||||
// Terminal states (held/cancelled/no_show/rescheduled) accept no further action.
|
||||
|
||||
export type AppointmentStatus = "scheduled" | "held" | "cancelled" | "no_show" | "rescheduled";
|
||||
export type LifecycleAction = "mark_held" | "mark_no_show" | "cancel" | "reschedule" | "reassign";
|
||||
|
||||
const ALLOWED_FROM: Record<LifecycleAction, readonly AppointmentStatus[]> = {
|
||||
mark_held: ["scheduled"],
|
||||
mark_no_show: ["scheduled"],
|
||||
cancel: ["scheduled"],
|
||||
reschedule: ["scheduled"],
|
||||
reassign: ["scheduled"],
|
||||
};
|
||||
|
||||
/** The status an action moves the appointment to, or null when it is unchanged. */
|
||||
const STATUS_AFTER: Record<LifecycleAction, AppointmentStatus | null> = {
|
||||
mark_held: "held",
|
||||
mark_no_show: "no_show",
|
||||
cancel: "cancelled",
|
||||
reschedule: "rescheduled",
|
||||
reassign: null,
|
||||
};
|
||||
|
||||
export class BookingTransitionError extends Error {
|
||||
readonly code = "invalid_transition";
|
||||
readonly from: AppointmentStatus;
|
||||
readonly action: LifecycleAction;
|
||||
constructor(from: AppointmentStatus, action: LifecycleAction) {
|
||||
super(`invalid_transition:${from}:${action}`);
|
||||
this.name = "BookingTransitionError";
|
||||
this.from = from;
|
||||
this.action = action;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when `action` is allowed from `status`. */
|
||||
export function canTransition(status: AppointmentStatus, action: LifecycleAction): boolean {
|
||||
return ALLOWED_FROM[action].includes(status);
|
||||
}
|
||||
|
||||
/** Throw BookingTransitionError unless `action` is allowed from `status`. */
|
||||
export function assertTransition(status: AppointmentStatus, action: LifecycleAction): void {
|
||||
if (!canTransition(status, action)) {
|
||||
throw new BookingTransitionError(status, action);
|
||||
}
|
||||
}
|
||||
|
||||
/** The resulting status for an action (null = unchanged, e.g. reassign). */
|
||||
export function statusAfter(action: LifecycleAction): AppointmentStatus | null {
|
||||
return STATUS_AFTER[action];
|
||||
}
|
||||
|
||||
/** Whether the action sends a customer-facing email (M06 Block I/D). */
|
||||
export function notifiesCustomer(action: LifecycleAction): boolean {
|
||||
return action === "cancel" || action === "reschedule" || action === "reassign";
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildIcs, icsToBase64 } from "./ics";
|
||||
|
||||
const base = {
|
||||
uid: "appt-123@hivegrid",
|
||||
start: new Date("2026-07-01T09:00:00Z"),
|
||||
end: new Date("2026-07-01T10:00:00Z"),
|
||||
dtstamp: new Date("2026-06-30T12:00:00Z"),
|
||||
summary: "Wartungstermin",
|
||||
};
|
||||
|
||||
describe("buildIcs (RFC 5545 minimal)", () => {
|
||||
it("emits a single VEVENT with UTC timestamps + CRLF endings", () => {
|
||||
const ics = buildIcs(base);
|
||||
expect(ics).toContain("BEGIN:VCALENDAR");
|
||||
expect(ics).toContain("BEGIN:VEVENT");
|
||||
expect(ics).toContain("UID:appt-123@hivegrid");
|
||||
expect(ics).toContain("DTSTART:20260701T090000Z");
|
||||
expect(ics).toContain("DTEND:20260701T100000Z");
|
||||
expect(ics).toContain("DTSTAMP:20260630T120000Z");
|
||||
expect(ics).toContain("SUMMARY:Wartungstermin");
|
||||
expect(ics).toContain("END:VCALENDAR");
|
||||
expect(ics).toContain("\r\n");
|
||||
});
|
||||
|
||||
it("escapes TEXT special chars (comma, semicolon, newline, backslash)", () => {
|
||||
const ics = buildIcs({ ...base, summary: "A, B; C\\D", description: "line1\nline2" });
|
||||
expect(ics).toContain("SUMMARY:A\\, B\\; C\\\\D");
|
||||
expect(ics).toContain("DESCRIPTION:line1\\nline2");
|
||||
});
|
||||
|
||||
it("includes organizer + attendee when provided", () => {
|
||||
const ics = buildIcs({ ...base, organizerEmail: "host@acme.de", organizerName: "Acme GmbH", attendeeEmail: "kunde@example.com" });
|
||||
expect(ics).toContain("ORGANIZER;CN=Acme GmbH:mailto:host@acme.de");
|
||||
expect(ics).toContain("ATTENDEE;ROLE=REQ-PARTICIPANT:mailto:kunde@example.com");
|
||||
});
|
||||
|
||||
it("omits optional fields when absent", () => {
|
||||
const ics = buildIcs(base);
|
||||
expect(ics).not.toContain("DESCRIPTION:");
|
||||
expect(ics).not.toContain("LOCATION:");
|
||||
expect(ics).not.toContain("ORGANIZER");
|
||||
});
|
||||
|
||||
it("base64-encodes round-trippable content", () => {
|
||||
const ics = buildIcs(base);
|
||||
expect(Buffer.from(icsToBase64(ics), "base64").toString("utf8")).toEqual(ics);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
// AK-P16b · minimal RFC-5545 .ics builder (PURE). The booking confirmation mail
|
||||
// attaches an "add to calendar" file; rather than pull a dependency we hand-roll the
|
||||
// tiny VEVENT subset the spec needs (EU/supply-chain clean, unit-tested). Only the
|
||||
// fields the confirmation needs: UID, DTSTAMP, DTSTART, DTEND, SUMMARY, DESCRIPTION,
|
||||
// LOCATION, optional ORGANIZER + ATTENDEE.
|
||||
|
||||
export interface IcsEventInput {
|
||||
readonly uid: string;
|
||||
readonly start: Date;
|
||||
readonly end: Date;
|
||||
readonly dtstamp: Date;
|
||||
readonly summary: string;
|
||||
readonly description?: string;
|
||||
readonly location?: string;
|
||||
readonly organizerEmail?: string;
|
||||
readonly organizerName?: string;
|
||||
readonly attendeeEmail?: string;
|
||||
}
|
||||
|
||||
/** Format a Date as an RFC-5545 UTC timestamp `YYYYMMDDTHHMMSSZ`. */
|
||||
function toIcsUtc(date: Date): string {
|
||||
return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
|
||||
}
|
||||
|
||||
/** Escape TEXT values per RFC 5545 §3.3.11 (backslash, semicolon, comma, newline). */
|
||||
function escapeText(value: string): string {
|
||||
return value.replace(/\\/g, "\\\\").replace(/;/g, "\\;").replace(/,/g, "\\,").replace(/\r?\n/g, "\\n");
|
||||
}
|
||||
|
||||
/** Fold a content line to <=75 octets per RFC 5545 §3.1 (CRLF + leading space). */
|
||||
function foldLine(line: string): string {
|
||||
if (line.length <= 75) {
|
||||
return line;
|
||||
}
|
||||
const parts: string[] = [line.slice(0, 75)];
|
||||
let rest = line.slice(75);
|
||||
while (rest.length > 74) {
|
||||
parts.push(` ${rest.slice(0, 74)}`);
|
||||
rest = rest.slice(74);
|
||||
}
|
||||
parts.push(` ${rest}`);
|
||||
return parts.join("\r\n");
|
||||
}
|
||||
|
||||
/** Build a single-VEVENT VCALENDAR string (CRLF line endings, as the spec mandates). */
|
||||
export function buildIcs(input: IcsEventInput): string {
|
||||
const lines: string[] = [
|
||||
"BEGIN:VCALENDAR",
|
||||
"VERSION:2.0",
|
||||
"PRODID:-//HiveGrid//Booking//EN",
|
||||
"CALSCALE:GREGORIAN",
|
||||
"METHOD:PUBLISH",
|
||||
"BEGIN:VEVENT",
|
||||
`UID:${input.uid}`,
|
||||
`DTSTAMP:${toIcsUtc(input.dtstamp)}`,
|
||||
`DTSTART:${toIcsUtc(input.start)}`,
|
||||
`DTEND:${toIcsUtc(input.end)}`,
|
||||
`SUMMARY:${escapeText(input.summary)}`,
|
||||
];
|
||||
if (input.description) {
|
||||
lines.push(`DESCRIPTION:${escapeText(input.description)}`);
|
||||
}
|
||||
if (input.location) {
|
||||
lines.push(`LOCATION:${escapeText(input.location)}`);
|
||||
}
|
||||
if (input.organizerEmail) {
|
||||
const cn = input.organizerName ? `;CN=${escapeText(input.organizerName)}` : "";
|
||||
lines.push(`ORGANIZER${cn}:mailto:${input.organizerEmail}`);
|
||||
}
|
||||
if (input.attendeeEmail) {
|
||||
lines.push(`ATTENDEE;ROLE=REQ-PARTICIPANT:mailto:${input.attendeeEmail}`);
|
||||
}
|
||||
lines.push("STATUS:CONFIRMED", "END:VEVENT", "END:VCALENDAR");
|
||||
return lines.map(foldLine).join("\r\n");
|
||||
}
|
||||
|
||||
/** Base64-encode an .ics string for use as a mail attachment `content`. */
|
||||
export function icsToBase64(ics: string): string {
|
||||
return Buffer.from(ics, "utf8").toString("base64");
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
computeSlots,
|
||||
pickFirstAvailableProvider,
|
||||
weekdayOfIsoDate,
|
||||
type ComputeSlotsInput,
|
||||
type ProviderAvailabilityInput,
|
||||
type SlotEngineConfig,
|
||||
} from "./slotEngine";
|
||||
|
||||
const TZ = "Europe/Berlin"; // UTC+2 in July (summer), UTC+1 in January (winter)
|
||||
const DATE = "2026-07-01";
|
||||
const NOW = new Date("2026-06-01T00:00:00Z"); // ~1 month out: passes notice + advance
|
||||
|
||||
const config = (over: Partial<SlotEngineConfig> = {}): SlotEngineConfig => ({
|
||||
durationMinutes: 60,
|
||||
bufferBeforeMinutes: 0,
|
||||
bufferAfterMinutes: 0,
|
||||
slotIncrementMinutes: 60,
|
||||
minNoticeHours: 4,
|
||||
maxAdvanceDays: 60,
|
||||
...over,
|
||||
});
|
||||
|
||||
const provider = (over: Partial<ProviderAvailabilityInput> = {}): ProviderAvailabilityInput => ({
|
||||
providerUserId: "u1",
|
||||
rules: [{ dayOfWeek: weekdayOfIsoDate(DATE), startTime: "09:00", endTime: "12:00", timezone: TZ }],
|
||||
exceptions: [],
|
||||
busyIntervals: [],
|
||||
...over,
|
||||
});
|
||||
|
||||
const run = (over: Partial<ComputeSlotsInput> = {}): ReturnType<typeof computeSlots> =>
|
||||
computeSlots({ date: DATE, now: NOW, providers: [provider()], config: config(), ...over });
|
||||
|
||||
const iso = (slots: ReturnType<typeof computeSlots>): string[] => slots.map((s) => s.startAt.toISOString());
|
||||
|
||||
describe("computeSlots (M06 A.6, timezone-aware)", () => {
|
||||
it("generates slots inside a single window, converted to UTC (Berlin summer = UTC+2)", () => {
|
||||
// 09:00-12:00 Berlin → 07:00-10:00 UTC; 60min slots stepping 60min.
|
||||
expect(iso(run())).toEqual(["2026-07-01T07:00:00.000Z", "2026-07-01T08:00:00.000Z", "2026-07-01T09:00:00.000Z"]);
|
||||
});
|
||||
|
||||
it("honours a lunch break (two rules on the same weekday)", () => {
|
||||
const weekday = weekdayOfIsoDate(DATE);
|
||||
const slots = run({
|
||||
providers: [
|
||||
provider({
|
||||
rules: [
|
||||
{ dayOfWeek: weekday, startTime: "09:00", endTime: "11:00", timezone: TZ },
|
||||
{ dayOfWeek: weekday, startTime: "14:00", endTime: "16:00", timezone: TZ },
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
// 09:00,10:00 + 14:00,15:00 Berlin → 07/08 + 12/13 UTC. Nothing 12:00-14:00 Berlin.
|
||||
expect(iso(slots)).toEqual([
|
||||
"2026-07-01T07:00:00.000Z",
|
||||
"2026-07-01T08:00:00.000Z",
|
||||
"2026-07-01T12:00:00.000Z",
|
||||
"2026-07-01T13:00:00.000Z",
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns no slots when an `unavailable` exception covers the day", () => {
|
||||
const slots = run({
|
||||
providers: [provider({ exceptions: [{ date: DATE, kind: "unavailable", startTime: null, endTime: null, timezone: TZ }] })],
|
||||
});
|
||||
expect(slots).toEqual([]);
|
||||
});
|
||||
|
||||
it("custom_window exception replaces the standard rule", () => {
|
||||
const slots = run({
|
||||
providers: [provider({ exceptions: [{ date: DATE, kind: "custom_window", startTime: "15:00", endTime: "17:00", timezone: TZ }] })],
|
||||
});
|
||||
// 15:00-17:00 Berlin → 13:00-15:00 UTC, one 60min slot at 13:00 + 14:00.
|
||||
expect(iso(slots)).toEqual(["2026-07-01T13:00:00.000Z", "2026-07-01T14:00:00.000Z"]);
|
||||
});
|
||||
|
||||
it("subtracts a busy interval (calendar/appointment) from the slots", () => {
|
||||
const slots = run({
|
||||
providers: [provider({ busyIntervals: [{ from: new Date("2026-07-01T08:00:00Z"), to: new Date("2026-07-01T09:00:00Z") }] })],
|
||||
});
|
||||
// 08:00 UTC slot removed; 07:00 + 09:00 remain.
|
||||
expect(iso(slots)).toEqual(["2026-07-01T07:00:00.000Z", "2026-07-01T09:00:00.000Z"]);
|
||||
});
|
||||
|
||||
it("applies buffer-after so an adjacent busy block knocks out the touching slot", () => {
|
||||
const slots = computeSlots({
|
||||
date: DATE,
|
||||
now: NOW,
|
||||
providers: [provider({ busyIntervals: [{ from: new Date("2026-07-01T08:15:00Z"), to: new Date("2026-07-01T08:30:00Z") }] })],
|
||||
config: config({ bufferAfterMinutes: 30 }),
|
||||
});
|
||||
// 07:00 slot ends 08:00, +30min buffer → occupies until 08:30, overlaps 08:15 busy → dropped.
|
||||
// 08:00 slot directly overlaps busy → dropped. Only 09:00 survives.
|
||||
expect(iso(slots)).toEqual(["2026-07-01T09:00:00.000Z"]);
|
||||
});
|
||||
|
||||
it("enforces min-notice (no slots inside the notice horizon)", () => {
|
||||
// now just before the day, minNotice 24h → 07:00/08:00/09:00 UTC all within 24h → none.
|
||||
const slots = run({ now: new Date("2026-07-01T00:00:00Z"), config: config({ minNoticeHours: 24 }) });
|
||||
expect(slots).toEqual([]);
|
||||
});
|
||||
|
||||
it("enforces max-advance (date beyond the booking horizon)", () => {
|
||||
const slots = run({ now: new Date("2026-01-01T00:00:00Z"), config: config({ maxAdvanceDays: 30 }) });
|
||||
expect(slots).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores rules for a different weekday", () => {
|
||||
const wrong = weekdayOfIsoDate(DATE) === "monday" ? "tuesday" : "monday";
|
||||
const slots = run({ providers: [provider({ rules: [{ dayOfWeek: wrong, startTime: "09:00", endTime: "12:00", timezone: TZ }] })] });
|
||||
expect(slots).toEqual([]);
|
||||
});
|
||||
|
||||
it("unions providers for first_available and picks the lowest-id provider", () => {
|
||||
const slots = run({
|
||||
providers: [
|
||||
provider({ providerUserId: "u2" }),
|
||||
provider({ providerUserId: "u1", busyIntervals: [{ from: new Date("2026-07-01T07:00:00Z"), to: new Date("2026-07-01T08:00:00Z") }] }),
|
||||
],
|
||||
});
|
||||
const first = slots.find((s) => s.startAt.toISOString() === "2026-07-01T07:00:00.000Z");
|
||||
expect(first?.providerUserIds).toEqual(["u2"]); // u1 busy at 07:00
|
||||
const second = slots.find((s) => s.startAt.toISOString() === "2026-07-01T08:00:00.000Z");
|
||||
expect(second?.providerUserIds).toEqual(["u1", "u2"]);
|
||||
expect(pickFirstAvailableProvider(second!)).toBe("u1");
|
||||
});
|
||||
|
||||
it("is DST-correct (Berlin winter = UTC+1)", () => {
|
||||
const winter = "2026-01-07";
|
||||
const slots = computeSlots({
|
||||
date: winter,
|
||||
now: new Date("2026-01-01T00:00:00Z"),
|
||||
providers: [provider({ rules: [{ dayOfWeek: weekdayOfIsoDate(winter), startTime: "09:00", endTime: "11:00", timezone: TZ }] })],
|
||||
config: config(),
|
||||
});
|
||||
// 09:00 Berlin winter → 08:00 UTC (not 07:00).
|
||||
expect(iso(slots)).toEqual(["2026-01-07T08:00:00.000Z", "2026-01-07T09:00:00.000Z"]);
|
||||
});
|
||||
});
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
// AK-P16b · slot engine (PURE, timezone-aware) — M06 Block A.6.
|
||||
//
|
||||
// Computes bookable start slots for a booking page on a given provider-local day.
|
||||
// No Prisma / no React: plain inputs in, UTC instants out. The loader-side wrapper
|
||||
// (SlotQueryService.server.ts) loads rows and pre-merges busy intervals; this file
|
||||
// holds only the deterministic, unit-testable arithmetic.
|
||||
//
|
||||
// Per provider, for the requested day:
|
||||
// windows = exceptions(date) OR weekly rules(weekday) (M06 A.4 overrides A.3)
|
||||
// for each window → step by slotIncrement, slot = [t, t+duration)
|
||||
// keep slot when its buffered range [t-bufferBefore, end+bufferAfter) does NOT
|
||||
// overlap the provider's busy intervals (other appointments ±buffer + Google
|
||||
// busy from AK-P16a availability.ts — leak-safe {from,to} only)
|
||||
// AND slot.start >= now + minNoticeHours AND slot.start <= now + maxAdvanceDays
|
||||
// `first_available` (v1): union all providers' slots, each slot carrying the ids of
|
||||
// every provider free at that exact instant.
|
||||
//
|
||||
// The requested `date` is the PROVIDER-LOCAL calendar date (each provider's rules /
|
||||
// exceptions carry their own IANA timezone). The public UI formats the returned UTC
|
||||
// instants in the viewer's timezone.
|
||||
|
||||
import { fromZonedTime } from "date-fns-tz";
|
||||
import { mergeBusyIntervals, overlapsBusy, type BusyInterval } from "~/modules/calendar/services/availability";
|
||||
|
||||
export type BookingWeekday = "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
|
||||
|
||||
const WEEKDAY_BY_UTC_DAY: readonly BookingWeekday[] = [
|
||||
"sunday",
|
||||
"monday",
|
||||
"tuesday",
|
||||
"wednesday",
|
||||
"thursday",
|
||||
"friday",
|
||||
"saturday",
|
||||
];
|
||||
|
||||
/** Weekly standard-availability window (local "HH:mm" in `timezone`). */
|
||||
export interface SlotRuleInput {
|
||||
readonly dayOfWeek: BookingWeekday;
|
||||
readonly startTime: string;
|
||||
readonly endTime: string;
|
||||
readonly timezone: string;
|
||||
}
|
||||
|
||||
/** Date-specific override. `unavailable` clears the day; `custom_window` replaces it. */
|
||||
export interface SlotExceptionInput {
|
||||
/** ISO calendar date `YYYY-MM-DD`. */
|
||||
readonly date: string;
|
||||
readonly kind: "unavailable" | "custom_window";
|
||||
readonly startTime: string | null;
|
||||
readonly endTime: string | null;
|
||||
readonly timezone: string;
|
||||
}
|
||||
|
||||
/** One provider's availability inputs. `busyIntervals` is pre-merged + leak-safe. */
|
||||
export interface ProviderAvailabilityInput {
|
||||
readonly providerUserId: string;
|
||||
readonly rules: readonly SlotRuleInput[];
|
||||
readonly exceptions: readonly SlotExceptionInput[];
|
||||
readonly busyIntervals: readonly BusyInterval[];
|
||||
}
|
||||
|
||||
/** Booking-page slot parameters (M06 A.1). */
|
||||
export interface SlotEngineConfig {
|
||||
readonly durationMinutes: number;
|
||||
readonly bufferBeforeMinutes: number;
|
||||
readonly bufferAfterMinutes: number;
|
||||
readonly slotIncrementMinutes: number;
|
||||
readonly minNoticeHours: number;
|
||||
readonly maxAdvanceDays: number;
|
||||
}
|
||||
|
||||
export interface ComputeSlotsInput {
|
||||
/** Provider-local calendar date `YYYY-MM-DD`. */
|
||||
readonly date: string;
|
||||
/** Injected wall clock (purity / testability). */
|
||||
readonly now: Date;
|
||||
readonly providers: readonly ProviderAvailabilityInput[];
|
||||
readonly config: SlotEngineConfig;
|
||||
}
|
||||
|
||||
/** A free slot. `providerUserIds` = everyone free at this exact instant (v1 union). */
|
||||
export interface ComputedSlot {
|
||||
readonly startAt: Date;
|
||||
readonly endAt: Date;
|
||||
readonly providerUserIds: string[];
|
||||
}
|
||||
|
||||
const MINUTE_MS = 60_000;
|
||||
const HOUR_MS = 3_600_000;
|
||||
const DAY_MS = 86_400_000;
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/u;
|
||||
|
||||
/** Weekday of an ISO `YYYY-MM-DD` (tz-independent — the date string has no zone). */
|
||||
export function weekdayOfIsoDate(date: string): BookingWeekday {
|
||||
return WEEKDAY_BY_UTC_DAY[new Date(`${date}T00:00:00Z`).getUTCDay()];
|
||||
}
|
||||
|
||||
/** Convert a local "HH:mm" on `date` in `timezone` to a UTC instant. */
|
||||
function localTimeToUtc(date: string, time: string, timezone: string): Date {
|
||||
return fromZonedTime(`${date}T${time}:00`, timezone);
|
||||
}
|
||||
|
||||
interface Window {
|
||||
readonly start: Date;
|
||||
readonly end: Date;
|
||||
}
|
||||
|
||||
/** Resolve the active windows for one provider on `date` (exceptions override rules). */
|
||||
function windowsForProvider(provider: ProviderAvailabilityInput, date: string): Window[] {
|
||||
const dayExceptions = provider.exceptions.filter((e) => e.date === date);
|
||||
if (dayExceptions.some((e) => e.kind === "unavailable")) {
|
||||
return [];
|
||||
}
|
||||
const customWindows = dayExceptions.filter((e) => e.kind === "custom_window" && e.startTime && e.endTime);
|
||||
if (customWindows.length > 0) {
|
||||
return customWindows
|
||||
.map((e) => ({ start: localTimeToUtc(date, e.startTime as string, e.timezone), end: localTimeToUtc(date, e.endTime as string, e.timezone) }))
|
||||
.filter((w) => w.end.getTime() > w.start.getTime());
|
||||
}
|
||||
const weekday = weekdayOfIsoDate(date);
|
||||
return provider.rules
|
||||
.filter((r) => r.dayOfWeek === weekday)
|
||||
.map((r) => ({ start: localTimeToUtc(date, r.startTime, r.timezone), end: localTimeToUtc(date, r.endTime, r.timezone) }))
|
||||
.filter((w) => w.end.getTime() > w.start.getTime());
|
||||
}
|
||||
|
||||
/** Compute bookable slots for one booking page on `date` across all providers. */
|
||||
export function computeSlots(input: ComputeSlotsInput): ComputedSlot[] {
|
||||
if (!ISO_DATE.test(input.date)) {
|
||||
return [];
|
||||
}
|
||||
const { config, now } = input;
|
||||
const earliest = now.getTime() + config.minNoticeHours * HOUR_MS;
|
||||
const latest = now.getTime() + config.maxAdvanceDays * DAY_MS;
|
||||
const durationMs = config.durationMinutes * MINUTE_MS;
|
||||
const stepMs = Math.max(config.slotIncrementMinutes, 1) * MINUTE_MS;
|
||||
const bufferBeforeMs = config.bufferBeforeMinutes * MINUTE_MS;
|
||||
const bufferAfterMs = config.bufferAfterMinutes * MINUTE_MS;
|
||||
|
||||
// instant(ms) → set of providers free there, so the union stays deduped + stable.
|
||||
const byInstant = new Map<number, { startAt: Date; endAt: Date; providers: Set<string> }>();
|
||||
|
||||
for (const provider of input.providers) {
|
||||
const busy = mergeBusyIntervals(provider.busyIntervals);
|
||||
for (const window of windowsForProvider(provider, input.date)) {
|
||||
for (let t = window.start.getTime(); t + durationMs <= window.end.getTime(); t += stepMs) {
|
||||
const startAt = new Date(t);
|
||||
const endAt = new Date(t + durationMs);
|
||||
if (t < earliest || t > latest) {
|
||||
continue;
|
||||
}
|
||||
// Buffered occupancy must be free of any existing busy block.
|
||||
if (overlapsBusy(new Date(t - bufferBeforeMs), new Date(t + durationMs + bufferAfterMs), busy)) {
|
||||
continue;
|
||||
}
|
||||
const existing = byInstant.get(t);
|
||||
if (existing) {
|
||||
existing.providers.add(provider.providerUserId);
|
||||
} else {
|
||||
byInstant.set(t, { startAt, endAt, providers: new Set([provider.providerUserId]) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...byInstant.values()]
|
||||
.sort((a, b) => a.startAt.getTime() - b.startAt.getTime())
|
||||
.map((s) => ({ startAt: s.startAt, endAt: s.endAt, providerUserIds: [...s.providers].sort() }));
|
||||
}
|
||||
|
||||
/**
|
||||
* `first_available` provider pick (M06 A.2 v1): the deterministic choice for a slot
|
||||
* is the lowest-id free provider. Returns null when nobody is free at that instant.
|
||||
*/
|
||||
export function pickFirstAvailableProvider(slot: ComputedSlot): string | null {
|
||||
return slot.providerUserIds.length > 0 ? slot.providerUserIds[0] : null;
|
||||
}
|
||||
Reference in new issue
Block a user