fix: harden booking and meeting flows

This commit is contained in:
2026-09-17 02:42:27 +02:00
parent cb30ecade9
commit 66710fc65c
42 changed files with 683 additions and 608 deletions
@@ -1,6 +1,8 @@
import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { combineDateAndTime } from "@/lib/meeting/status";
import { withBookingTransaction } from "@/lib/booking/transaction";
export const dynamic = "force-dynamic";
@@ -19,31 +21,40 @@ export async function POST(request: Request, { params }: Args) {
return NextResponse.json({ error: "Bitte bestätige zuerst deine E-Mail-Adresse.", code: "EMAIL_NOT_VERIFIED" }, { status: 403 });
}
const booking = await payload.findByID({ collection: "booking-requests", id, depth: 0 }).catch(() => null);
if (!booking || Number(booking.user) !== Number(user.id)) {
return NextResponse.json({ error: "Buchung nicht gefunden." }, { status: 404 });
}
const alternative = booking.proposedAlternative;
if (booking.status !== "pending" || !alternative?.date || !alternative.startTime || !alternative.endTime) {
return NextResponse.json({ error: "Für diese Buchung liegt kein alternativer Termin vor." }, { status: 409 });
}
return await withBookingTransaction(payload, `booking:${id}`, async (req) => {
const { docs } = await payload.find({ collection: "booking-requests", where: { id: { equals: id } }, depth: 0, limit: 1, req });
const booking = docs[0];
if (!booking || Number(booking.user) !== Number(user.id)) {
return NextResponse.json({ error: "Buchung nicht gefunden." }, { status: 404 });
}
const alternative = booking.proposedAlternative;
if (booking.status !== "pending" || !alternative?.date || !alternative.startTime || !alternative.endTime) {
return NextResponse.json({ error: "Für diese Buchung liegt kein alternativer Termin vor." }, { status: 409 });
}
// The beforeChange hook on booking-requests re-checks for conflicts
// (with an advisory lock) before allowing this to become "confirmed" —
// the alternative slot may have been taken by someone else since it was
// proposed.
await payload.update({
collection: "booking-requests",
id,
data: {
status: "confirmed",
date: alternative.date,
startTime: alternative.startTime,
endTime: alternative.endTime,
},
const alternativeStart = combineDateAndTime(alternative.date, alternative.startTime);
if (!Number.isFinite(alternativeStart.getTime()) || alternativeStart <= new Date()) {
return NextResponse.json({ error: "Dieser Terminvorschlag liegt bereits in der Vergangenheit." }, { status: 409 });
}
// The beforeChange hook on booking-requests re-checks for conflicts
// (with an advisory lock) before allowing this to become "confirmed" —
// the alternative slot may have been taken by someone else since it was
// proposed.
await payload.update({
collection: "booking-requests",
id,
req,
data: {
status: "confirmed",
date: alternative.date,
startTime: alternative.startTime,
endTime: alternative.endTime,
},
});
return NextResponse.json({ ok: true });
});
return NextResponse.json({ ok: true });
} catch (error) {
if (error instanceof Error && "status" in error && (error as { status: number }).status === 409) {
return NextResponse.json({ error: error.message }, { status: 409 });
+13 -9
View File
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { withBookingTransaction } from "@/lib/booking/transaction";
export const dynamic = "force-dynamic";
@@ -18,16 +19,19 @@ export async function POST(request: Request, { params }: Args) {
// Cancelling is deliberately allowed regardless of verification status —
// only creating/confirming a booking is a gated "protected" action.
const booking = await payload.findByID({ collection: "booking-requests", id, depth: 0 }).catch(() => null);
if (!booking || Number(booking.user) !== Number(user.id)) {
return NextResponse.json({ error: "Buchung nicht gefunden." }, { status: 404 });
}
if (booking.status === "cancelled") {
return NextResponse.json({ ok: true });
}
return await withBookingTransaction(payload, `booking:${id}`, async (req) => {
const { docs } = await payload.find({ collection: "booking-requests", where: { id: { equals: id } }, depth: 0, limit: 1, req });
const booking = docs[0];
if (!booking || Number(booking.user) !== Number(user.id)) {
return NextResponse.json({ error: "Buchung nicht gefunden." }, { status: 404 });
}
if (booking.status === "cancelled") {
return NextResponse.json({ ok: true });
}
await payload.update({ collection: "booking-requests", id, data: { status: "cancelled" } });
return NextResponse.json({ ok: true });
await payload.update({ collection: "booking-requests", id, req, data: { status: "cancelled" } });
return NextResponse.json({ ok: true });
});
} catch (error) {
console.error("booking cancel failed", error);
return NextResponse.json({ error: "Der Termin konnte nicht storniert werden." }, { status: 500 });
+46 -25
View File
@@ -2,6 +2,8 @@ import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { getAvailableSlots } from "@/lib/booking/slots";
import { withBookingTransaction } from "@/lib/booking/transaction";
import { checkRateLimit, getClientIp } from "@/lib/auth/rateLimit";
import { berlinDayBounds } from "@/lib/calendar/timezone";
export const dynamic = "force-dynamic";
@@ -17,13 +19,15 @@ export async function POST(request: Request) {
let body: Body;
try {
body = await request.json();
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid body");
} catch {
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
}
const offerSlug = typeof body.offerSlug === "string" ? body.offerSlug : "";
const startISO = typeof body.start === "string" ? body.start : "";
const appointmentType = body.appointmentType === "online" ? "online" : "onsite";
const appointmentType = body.appointmentType;
if (appointmentType !== "online" && appointmentType !== "onsite") return NextResponse.json({ error: "Ungültige Terminart." }, { status: 400 });
const message = typeof body.message === "string" ? body.message.trim().slice(0, 2000) : "";
if (!offerSlug || !startISO) {
@@ -40,6 +44,11 @@ export async function POST(request: Request) {
return NextResponse.json({ error: "Bitte bestätige zuerst deine E-Mail-Adresse.", code: "EMAIL_NOT_VERIFIED" }, { status: 403 });
}
if (!checkRateLimit(`booking:ip:${getClientIp(request)}`, { max: 30, windowMs: 3600000 }) ||
!checkRateLimit(`booking:customer:${user.id}`, { max: 10, windowMs: 3600000 })) {
return NextResponse.json({ error: "Zu viele Terminanfragen. Bitte versuche es später erneut." }, { status: 429 });
}
const { docs } = await payload.find({
collection: "offers",
where: { slug: { equals: offerSlug } },
@@ -61,32 +70,44 @@ export async function POST(request: Request) {
// stale slot list) — the hard, race-safe check still runs again when
// Anna confirms (see collections/BookingRequests.ts).
const dayBounds = berlinDayBounds(start);
const slotsByDay = await getAvailableSlots(payload, {
durationMinutes: offer.durationMinutes,
from: dayBounds.start,
to: dayBounds.end,
});
const key = dayBounds.key;
const isStillFree = (slotsByDay.get(key) ?? []).some((s) => s.start.getTime() === start.getTime());
if (!isStillFree) {
return NextResponse.json({ error: "Dieser Termin ist leider nicht mehr verfügbar." }, { status: 409 });
}
return await withBookingTransaction(payload, dayBounds.key, async (req) => {
const { docs: existing } = await payload.find({ collection: "booking-requests", req, depth: 0, limit: 1,
where: { and: [
{ user: { equals: user.id } }, { offer: { equals: offer.id } },
{ startTime: { equals: start.toISOString() } }, { appointmentType: { equals: appointmentType } },
{ status: { in: ["pending", "confirmed"] } },
] },
});
if (existing[0]) return NextResponse.json({ ok: true });
const slotsByDay = await getAvailableSlots(payload, {
durationMinutes: offer.durationMinutes!,
req,
from: dayBounds.start,
to: dayBounds.end,
});
const key = dayBounds.key;
const isStillFree = (slotsByDay.get(key) ?? []).some((s) => s.start.getTime() === start.getTime());
if (!isStillFree) {
return NextResponse.json({ error: "Dieser Termin ist leider nicht mehr verfügbar." }, { status: 409 });
}
await payload.create({
collection: "booking-requests",
data: {
user: user.id,
offer: offer.id,
date: start.toISOString(),
startTime: start.toISOString(),
endTime: end.toISOString(),
appointmentType,
status: "pending",
userMessage: message || undefined,
},
});
await payload.create({
collection: "booking-requests",
req,
data: {
user: user.id,
offer: offer.id,
date: start.toISOString(),
startTime: start.toISOString(),
endTime: end.toISOString(),
appointmentType,
status: "pending",
userMessage: message || undefined,
},
});
return NextResponse.json({ ok: true });
return NextResponse.json({ ok: true });
});
} catch (error) {
console.error("booking request failed", error);
return NextResponse.json({ error: "Die Anfrage konnte nicht gesendet werden. Bitte versuche es später erneut." }, { status: 500 });
+6 -6
View File
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { getAvailableSlots } from "@/lib/booking/slots";
import { berlinDayBounds, parseBerlinDate } from "@/lib/calendar/timezone";
export const dynamic = "force-dynamic";
@@ -29,16 +30,15 @@ export async function GET(request: Request) {
return NextResponse.json({ error: "Dieses Angebot ist nicht buchbar." }, { status: 404 });
}
const from = fromParam ? new Date(`${fromParam}T00:00:00`) : new Date();
if (Number.isNaN(from.getTime())) {
const from = fromParam ? parseBerlinDate(fromParam) : berlinDayBounds(new Date()).start;
if (!from) {
return NextResponse.json({ error: "Ungültiges Startdatum." }, { status: 400 });
}
from.setHours(0, 0, 0, 0);
const to = toParam ? new Date(`${toParam}T00:00:00`) : new Date(from.getTime() + 21 * 24 * 60 * 60 * 1000);
if (Number.isNaN(to.getTime())) {
const toDate = toParam ? parseBerlinDate(toParam) : new Date(from.getTime() + 21 * 24 * 60 * 60 * 1000);
if (!toDate) {
return NextResponse.json({ error: "Ungültiges Enddatum." }, { status: 400 });
}
to.setHours(23, 59, 59, 999);
const to = berlinDayBounds(toDate).end;
if (to < from) {
return NextResponse.json({ error: "Das Enddatum muss nach dem Startdatum liegen." }, { status: 400 });